/* $RCSFile: 2.2.2.0000.sql $
 Apache license v2 2011 by Christian Surieux
 Removing this comment is forbiddden
 $Source: ?/AddonNice/Setup/Scripts/2.2.2.0000.sql $
 $log$
 Revision 37 2010/08/09 12:26:56  christian.surieux
   Adding Log comment to sql files
*/
---------------------
--2.2.2.0000.sql
---------------------

-- CLEAN INSTALL for system tables AND procedures
-- Modules structures will be created by module itself

-- not necessary when executed from program, use only when manual execute 
-- USE [AddonNice]

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

-- PORTALS
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_Portals]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_Portals] (
	[PortalID] [int] IDENTITY (-1, 1) NOT NULL ,
	[PortalAlias] [nvarchar] (128) NOT NULL ,
	[PortalName] [nvarchar] (128) NOT NULL ,
	[PortalPath] [nvarchar] (128) NULL ,
	[PortalType] int NOT NULL CONSTRAINT [DF_adn_Portals_Type]  DEFAULT (0),
	CONSTRAINT [PK_adn_Portals] PRIMARY KEY NONCLUSTERED 
	(
		[PortalID]
	),
	CONSTRAINT [IX_adn_Portals] UNIQUE  NONCLUSTERED 
	(
		[PortalAlias]
	)
)
END
GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_PortalAlias]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_PortalAlias] (
	[PortalID] [int] NOT NULL ,
	[PortalAlias] [nvarchar] (128) NOT NULL ,
	CONSTRAINT [IX_adn_PortalAlias] PRIMARY KEY NONCLUSTERED 
	(
		[PortalAlias]
	),
	CONSTRAINT [FK_adn_PortalAlias_adn_Portals] FOREIGN KEY 
	(
		[PortalID]
	) REFERENCES [dbo].[adn_Portals] (
		[PortalID]
	)
)
END
GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_PortalSettings]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_PortalSettings] (
	[PortalID] [int] NOT NULL ,
	[SettingName] [nvarchar] (50) NOT NULL ,
	[SettingValue] [nvarchar] (1500) NOT NULL ,
	CONSTRAINT [PK_adn_PortalSettings] PRIMARY KEY CLUSTERED 
	(
		[PortalID],
		[SettingName]
	),
	CONSTRAINT [FK_adn_PortalSettings_adn_Portals] FOREIGN KEY 
	(
		[PortalID]
	) REFERENCES [dbo].[adn_Portals] (
		[PortalID]
	) ON DELETE CASCADE  
)
 CREATE  INDEX [IX_adn_PortalSettings] ON [dbo].[adn_PortalSettings]([PortalID], [SettingName])
END
GO

-- CRM Servers
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_CrmServer]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_CrmServer] (
	CrmServerID int IDENTITY (0, 1) NOT NULL ,
	FriendlyName [nvarchar] (128),
	CrmVersion [int] NOT NULL,
    UsePreAuthenticate [bit] NOT NULL,
	Organization [nvarchar] (256) NOT NULL,
	AuthenticationType [int] NOT NULL,
	DiscoServer [nvarchar] (256) NOT NULL,
	DiscoServerPort [int] NOT NULL,
	Server3 [nvarchar] (256) NULL,
	ServiceAccount [nvarchar] (128) NOT NULL,
	ServicePassword [nvarchar] (128) NOT NULL,
	ServiceDomain [nvarchar] (128) NOT NULL,
	PrivAccount [nvarchar] (128) NOT NULL,
	PrivPassword [nvarchar] (128) NOT NULL,
	PrivDomain [nvarchar] (128) NOT NULL,
	DefaultAccount [nvarchar] (128) NOT NULL,
	DefaultAccountPassword [nvarchar] (128) NOT NULL,
	DefaultAccountDomain [nvarchar] (128) NOT NULL,
	AdminRoleName [nvarchar] (128) NOT NULL,
	MainPortalID [int] NULL ,
	CONSTRAINT [PK_adn_CrmServer] PRIMARY KEY NONCLUSTERED 
	(
		[CrmServerID]
	),
	CONSTRAINT [IX_adn_CrmServer] UNIQUE  NONCLUSTERED 
	(
		[FriendlyName]
	),
	CONSTRAINT [IX_adn_CrmServer2] UNIQUE  NONCLUSTERED 
	(
		[DiscoServer],
		[Organization]
	)
)
END
GO

-- Crm Server Portal
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_PortalCrmServer]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_PortalCrmServer] (
	PortalId [int] NOT NULL, 
	CrmServerID [int] NOT NULL,
	CONSTRAINT [IX_adn_PortalCrmServer] UNIQUE CLUSTERED 
	(
		[PortalId],
		[CrmServerID]
	),
	CONSTRAINT [IX2_adn_PortalCrmServer] UNIQUE 
	(
		[PortalId]
	),
	CONSTRAINT [FK_adn_PortalCrmServer_adn_Portals] FOREIGN KEY 
	(
		[PortalId]
	) REFERENCES [dbo].[adn_Portals] (
		[PortalId]
	),
	CONSTRAINT [FK_PortalCrmServer_adn_CrmServer] FOREIGN KEY 
	(
		[CrmServerId]
	) REFERENCES [dbo].[adn_CrmServer] (
		[CrmServerId]
	)
)
END
GO

-- Crm entity
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_CrmEntity]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_CrmEntity] (
	EntityId [int] IDENTITY (0, 1) NOT NULL ,
	SchemaName [nvarchar] (128) NOT NULL,
	EntityVersion [nvarchar] (16) NOT NULL,
	FriendlyName [nvarchar] (128) NULL,
    InitClass [nvarchar] (128) NULL,
    LoadAssembly [nvarchar] (128) NULL,
	[PackageName] [nvarchar] (50) NULL,   
	NeedCreateBuilder [bit] NOT NULL,
	NeedExtendBuilder [bit] NOT NULL,
	NeedUIBuilder [bit] NOT NULL,
	CONSTRAINT [PK_adn_CrmEntity] PRIMARY KEY CLUSTERED 
	(
		[EntityId]
	),
	CONSTRAINT [IX_adn_CrmEntity] UNIQUE NONCLUSTERED 
	(
		[SchemaName],
		[EntityVersion]
	)
)
END
GO

-- Crm Server / Entity
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_ServerEntity]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_ServerEntity] (
	EntityId [int] NOT NULL,
	CrmServerId [int] NOT NULL,
	InstalledVersion [nvarchar] (16) NOT NULL,
	InstallDate [DateTime],
	CONSTRAINT [IX_adn_ServerEntity] UNIQUE NONCLUSTERED 
	(
		[EntityId],
		[CrmServerId]
		),
	CONSTRAINT [FK_adn_ServerEntity_adn_CrmServer] FOREIGN KEY 
	(
		CrmServerId
	) REFERENCES [dbo].[adn_CrmServer]
	(
		CrmServerId
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_adn_ServerEntity_adn_CrmEntity] FOREIGN KEY 
	(
		EntityId
	) REFERENCES [dbo].[adn_CrmEntity]
	(
		EntityId
	) ON DELETE CASCADE
)
END
GO

-- Pages ou Tabs
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_Tabs]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_Tabs] (
	[TabID]			[int] IDENTITY (1, 1) NOT NULL ,
	[ParentTabID]	[int] NULL ,
	[TabOrder]		[int] NOT NULL ,
	[PortalID]		[int] NOT NULL ,
	[TabLayout]		[int] NULL ,
	[NbPanes]		[int] NOT NULL CONSTRAINT [DF_adn_Tabs_NbPanes]  DEFAULT (3),
	[Width0]		[int] NOT NULL CONSTRAINT [DF_adn_Tabs_Width0]  DEFAULT (0),
	[Width1]		[int] NOT NULL CONSTRAINT [DF_adn_Tabs_Width1]  DEFAULT (0),
	[Width2]		[int] NOT NULL CONSTRAINT [DF_adn_Tabs_Width2]  DEFAULT (0),
	[Width3]		[int] NOT NULL CONSTRAINT [DF_adn_Tabs_Width3]  DEFAULT (0),
	[Width4]		[int] NOT NULL CONSTRAINT [DF_adn_Tabs_Width4]  DEFAULT (0),
	[TabName]		[nvarchar] (50) NOT NULL ,
	[UrlName]		[nvarchar] (50) NULL ,
	[TabSkinID]		[nvarchar](50) NOT NULL CONSTRAINT [DF_adn_Tabs_TabSkinID]  DEFAULT (''),
	[AuthorizedRoles] [nvarchar] (512) NULL ,
	CONSTRAINT [PK_adn_Tabs] PRIMARY KEY NONCLUSTERED 
	(
		[TabID]
	),
	CONSTRAINT [FK_adn_Tabs_adn_Portals] FOREIGN KEY 
	(
	PortalID
	) REFERENCES [dbo].[adn_Portals]
	(
	PortalID
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_adn_Tabs_adn_Tabs] FOREIGN KEY 
	(
		[ParentTabID]
	) REFERENCES [dbo].[adn_Tabs] (
		[TabID]
	)
)
END
GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_SiteMap]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_SiteMap] 
(
	[PortalID] [int] NOT NULL ,
	[PageID] [int] NOT NULL ,
	[ParentPageID] [int] NULL ,
	[PageOrder] [int] NOT NULL ,
	CONSTRAINT [PK_adn_SiteMap] PRIMARY KEY NONCLUSTERED 
	(
		[PageID]
	),
	CONSTRAINT [FK_adn_SiteMap_adn_Tabs_1] FOREIGN KEY 
	(
		[PageID]
	) REFERENCES [dbo].[adn_Tabs] (
		[TabID]
	),
	CONSTRAINT [FK_adn_SiteMap_adn_Tabs_2] FOREIGN KEY 
	(
		[ParentPageID]
	) REFERENCES [dbo].[adn_Tabs] (
		[TabID]
	)
)
END
GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_TabSettings]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_TabSettings] (
	[TabID] [int] NOT NULL ,
	[SettingName] [nvarchar] (50) NOT NULL ,
	[SettingValue] [nvarchar] (1500) NOT NULL ,
	CONSTRAINT [PK_adn_Tabsettings] PRIMARY KEY CLUSTERED 
	(
		[TabID],
		[SettingName]
	),
	CONSTRAINT [FK_adn_Tabsettings_adn_Tabs] FOREIGN KEY 
	(
		[TabID]
	) REFERENCES [dbo].[adn_Tabs] (
		[TabID]
	) ON DELETE CASCADE 
)
END
GO

-- Modules definitions
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GeneralModuleDefinitions]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_GeneralModuleDefinitions](
	[GeneralModDefID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[VersionType] int NOT NULL,
	[Admin] [bit] NULL CONSTRAINT [DF_adn_GeneralModuleDefinitions_Admin]  DEFAULT ((0)),
	[Lock] [bit] NULL CONSTRAINT [DF_adn_GeneralModuleDefinitions_Lock]  DEFAULT ((0)),
	[Category] [nvarchar](128) NOT NULL CONSTRAINT [DF_adn_GeneralModuleDefinitions_Category]  DEFAULT ('Normal'),
	[FriendlyName] [nvarchar](128) NOT NULL,
	[DesktopSrc] [nvarchar](256) NOT NULL,
	[AssemblyName] [varchar](50) NOT NULL CONSTRAINT [DF_adn_GeneralModuleDefinitions_AssemblyName]  DEFAULT ('AddonNice.DLL'),
	[ClassName] [nvarchar](128) NULL,
	[Usage] [nvarchar](1024) NULL,
 CONSTRAINT [PK_adn_GeneralModuleDefinitions] PRIMARY KEY CLUSTERED 
(
	[GeneralModDefID] ASC
) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [IX_adn_GeneralModuleDefinitions] UNIQUE NONCLUSTERED 
(
	[FriendlyName] ASC
) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO

-- GeneralModuleDefinitions/CrmEntity
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_ModuleEntity]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_ModuleEntity] (
	EntityId [int] NOT NULL, 
	ModuleDefId [uniqueidentifier] NOT NULL,
	CONSTRAINT [IX_adn_ModuleEntity] UNIQUE CLUSTERED 
	(
		[EntityId],
		[ModuleDefId]
	),
	CONSTRAINT [FK_adn_ModuleEntity_adn_GeneralModuleDefinitions] FOREIGN KEY 
	(
		[ModuleDefId]
	) REFERENCES [dbo].[adn_GeneralModuleDefinitions] (
		[GeneralModDefID]
	),
	CONSTRAINT [FK_adn_ModuleEntity_adn_CrmEntity] FOREIGN KEY 
	(
		[EntityId]
	) REFERENCES [dbo].[adn_CrmEntity] (
		[EntityId]
	)
)
END
GO


IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_ModuleDefinitions]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_ModuleDefinitions] (
	[ModuleDefID] [int] IDENTITY (1, 1) NOT NULL ,
	[PortalID] [int] NOT NULL ,
	[GeneralModDefID] [uniqueidentifier] NOT NULL ,
	CONSTRAINT [PK_adn_ModuleDefinitions] PRIMARY KEY NONCLUSTERED 
	(
		[ModuleDefID]
	),
	CONSTRAINT [FK_adn_ModuleDefinitions_adn_GeneralModuleDefinitions] FOREIGN KEY 
	(
		[GeneralModDefID]
	) REFERENCES [dbo].[adn_GeneralModuleDefinitions] (
		[GeneralModDefID]
	) ON DELETE CASCADE 
)
END

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_Modules]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_Modules] (
	[ModuleID] [int] IDENTITY (1, 1) NOT NULL ,
	[TabID] [int] NOT NULL,
	[ModuleDefID] [int] NOT NULL,
	[ModuleOrder] [int] NOT NULL ,
	[PaneName] [nvarchar] (50) NOT NULL ,
	[ModuleSettingsID] [int] NOT NULL CONSTRAINT [DF_adn_Modules_ModuleSettingsID] DEFAULT (0),
	[ModuleTitle] [nvarchar] (256) NULL ,
	[AuthorizedEditRoles] [nvarchar] (512) NULL ,
	[AuthorizedViewRoles] [nvarchar] (512) NULL ,
	[AuthorizedAddRoles] [nvarchar] (512) NULL ,
	[AuthorizedDeleteRoles] [nvarchar] (512) NULL ,
	[AuthorizedPropertiesRoles] [nvarchar] (512) NULL ,
	[AuthorizedMoveModuleRoles] [nvarchar] (512) NULL, 
	[AuthorizedDeleteModuleRoles] [nvarchar] (512) NULL, 
	[CacheTime] [int] NOT NULL ,
	[NewVersion] [bit] NULL CONSTRAINT [DF_adn_Modules_NewVersion] DEFAULT (1),
	[LastModified] [datetime] NULL ,
	[LastEditor] [nvarchar] (256) NULL ,
	[SupportCollapsable] [bit] NULL CONSTRAINT [DF_adn_Modules_SupportCollapsable] DEFAULT (0),
	[ShowEveryWhere] [bit] NULL CONSTRAINT [DF_adn_Modules_ShowEveryWhere] DEFAULT (0),
	CONSTRAINT [PK_adn_Modules] PRIMARY KEY NONCLUSTERED 
	(
		[ModuleID]
	),
	CONSTRAINT [FK_adn_Modules_adn_ModuleDefinitions] FOREIGN KEY  
	(
		[ModuleDefID]
	) REFERENCES [dbo].[adn_ModuleDefinitions] (
		[ModuleDefID]
	) ON DELETE CASCADE,
	CONSTRAINT [FK_adn_Modules_adn_Tabs] FOREIGN KEY 
	(
	TabID
	) REFERENCES [dbo].[adn_Tabs]
	(
	TabID
	) ON DELETE CASCADE
)
END
GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_ModuleSettings]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_ModuleSettings] (
	[ModuleID] [int] NOT NULL ,
	[SettingGroup] [int] NOT NULL CONSTRAINT [DF_adn_ModuleSettings_SettingGroup]  DEFAULT ((0)),
	[SettingName] [nvarchar] (50) NOT NULL ,
	[SettingValue] [nvarchar] (1500) NOT NULL ,
	CONSTRAINT [PK_adn_ModuleSettings] PRIMARY KEY  CLUSTERED 
	(
		[ModuleID],
		[SettingName]
	),
	CONSTRAINT [FK_adn_ModuleSettings_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  
)
 CREATE  INDEX [IX_adn_ModuleSettings] ON [dbo].[adn_ModuleSettings]([ModuleID], [SettingName])
END
GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UserDesktop]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_UserDesktop] (
	[UserID] [uniqueidentifier] NOT NULL ,
	[ModuleID] [int] NOT NULL ,
	[TabID] [int] NOT NULL ,
	[PortalID] [int] NOT NULL ,
	[State] [smallint] NOT NULL ,
	CONSTRAINT [PK_adn_UserDesktop] PRIMARY KEY  CLUSTERED 
	(
		[UserID],
		[ModuleID],
		[TabID],
		[PortalID]
	) 
)
END
GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_Versions]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_Versions] (
	[Release] [int] NOT NULL ,
	[Version] [nvarchar] (50) NULL ,
	[ReleaseDate] [datetime] NULL 
) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_Packages]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_Packages] (
	[PackageName] [nvarchar] (50) NULL ,
	[Release] [int] NOT NULL ,
	[Version] [nvarchar] (50) NULL ,
	[ReleaseDate] [datetime] NULL 
) ON [PRIMARY]
END
GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_ModuleUserSettings]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_ModuleUserSettings] (
	[ModuleID] [int] NOT NULL ,
	[SettingGroup] [int] NOT NULL CONSTRAINT [DF_adn_ModuleUserSettings_SettingGroup]  DEFAULT ((0)),
	[UserID] [uniqueidentifier] NOT NULL ,
	[SettingName] [nvarchar] (50) NOT NULL ,
	[SettingValue] [nvarchar] (1500) NOT NULL ,
	CONSTRAINT [PK_adn_ModuleUserSettings] PRIMARY KEY  CLUSTERED 
	(
		[ModuleID],
		[UserID] ,
		[SettingName]
	),
	CONSTRAINT [FK_adn_ModuleUserSettings_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  
)
 CREATE  INDEX [IX_adn_ModuleUserSettings] ON [dbo].[adn_ModuleUserSettings]([ModuleID], [USerID], [SettingName])
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_Recycler]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_Recycler] (
	[ModuleID] [int] NOT NULL ,
	[DateDeleted] [datetime] NOT NULL ,
	[DeletedBy] [nvarchar] (250) NULL ,
	[OriginalTab] [int] NOT NULL 
) ON [PRIMARY]
END
GO


--*********************************************
--**           STORED PROCEDURES             **
--*********************************************

-- Crm Servers
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAllCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllCrmServer]
GO

CREATE PROCEDURE [dbo].[adn_GetAllCrmServer]
AS
SELECT * FROM adn_CrmServer 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetCrmServer]
GO

CREATE PROCEDURE [dbo].[adn_GetCrmServer]
(
	@CrmServerID     int
)
AS
SELECT * FROM adn_CrmServer WHERE CrmServerID = @CrmServerID
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteCrmServer]
GO

CREATE PROCEDURE [dbo].[adn_DeleteCrmServer]
(
	@CrmServerID     int
)
AS
DELETE FROM adn_CrmServer WHERE CrmServerID = @CrmServerID
GO


IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateCrmServer]
GO

CREATE PROCEDURE [dbo].[adn_UpdateCrmServer]
(
	@CrmServerID int,
	@FriendlyName [nvarchar] (128),
	@CrmVersion [int],
    @UsePreAuthenticate [bit],
	@Organization [nvarchar] (256),
	@AuthenticationType [int],
	@DiscoServer [nvarchar] (256),
	@DiscoServerPort [int],
	@Server3 [nvarchar] (256),
	@ServiceAccount [nvarchar] (128),
	@ServicePassword [nvarchar] (128),
	@ServiceDomain [nvarchar] (128),
	@PrivAccount [nvarchar] (128),
	@PrivPassword [nvarchar] (128),
	@PrivDomain [nvarchar] (128),
	@DefaultAccount [nvarchar] (128),
	@DefaultAccountPassword [nvarchar] (128),
	@DefaultAccountDomain [nvarchar] (128),
	@AdminRoleName [nvarchar] (128)
)
AS
UPDATE adn_CrmServer SET
	FriendlyName		=	@FriendlyName,
	CrmVersion			=	@CrmVersion,
    UsePreAuthenticate	=	@UsePreAuthenticate,
	Organization		=	@Organization,
	AuthenticationType	=	@AuthenticationType,
	DiscoServer			=	@DiscoServer,
	DiscoServerPort		=	@DiscoServerPort,
	Server3				=	@Server3,
	ServiceAccount		=	@ServiceAccount,
	ServicePassword		=	@ServicePassword,
	ServiceDomain		=	@ServiceDomain,
	PrivAccount			=	@PrivAccount,
	PrivPassword		=	@PrivPassword,
	PrivDomain			=	@PrivDomain,
	DefaultAccount		=	@DefaultAccount,
	DefaultAccountPassword	=	@DefaultAccountPassword,
	DefaultAccountDomain	=	@DefaultAccountDomain,
	AdminRoleName			=	@AdminRoleName
WHERE CrmServerId = @CrmServerId
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddCrmServer]
GO

CREATE PROCEDURE [dbo].[adn_AddCrmServer]
(
	@FriendlyName [nvarchar] (128),
	@CrmVersion [int],
    @UsePreAuthenticate [bit],
	@Organization [nvarchar] (256),
	@AuthenticationType [int],
	@DiscoServer [nvarchar] (256),
	@DiscoServerPort [int],
	@Server3 [nvarchar] (256),
	@ServiceAccount [nvarchar] (128),
	@ServicePassword [nvarchar] (128),
	@ServiceDomain [nvarchar] (128),
	@PrivAccount [nvarchar] (128),
	@PrivPassword [nvarchar] (128),
	@PrivDomain [nvarchar] (128),
	@DefaultAccount [nvarchar] (128),
	@DefaultAccountPassword [nvarchar] (128),
	@DefaultAccountDomain [nvarchar] (128),
	@AdminRoleName [nvarchar] (128),
	@CrmServerId     int OUTPUT
)
AS
INSERT INTO adn_CrmServer
(
	FriendlyName,
	CrmVersion,
    UsePreAuthenticate,
	Organization,
	AuthenticationType,
	DiscoServer,
	DiscoServerPort,
	Server3,
	ServiceAccount,
	ServicePassword,
	ServiceDomain,
	PrivAccount,
	PrivPassword,
	PrivDomain,
	DefaultAccount,
	DefaultAccountPassword,
	DefaultAccountDomain,
	AdminRoleName
) 
VALUES
(
	@FriendlyName,
	@CrmVersion,
    @UsePreAuthenticate,
	@Organization,
	@AuthenticationType,
	@DiscoServer,
	@DiscoServerPort,
	@Server3,
	@ServiceAccount,
	@ServicePassword,
	@ServiceDomain,
	@PrivAccount,
	@PrivPassword,
	@PrivDomain,
	@DefaultAccount,
	@DefaultAccountPassword,
	@DefaultAccountDomain,
	@AdminRoleName
)
SELECT @CrmServerId = @@IDENTITY
GO

-- Portal CrmServer 

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetFirstCrmServerByPortal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFirstCrmServerByPortal]
GO

CREATE PROCEDURE [dbo].[adn_GetFirstCrmServerByPortal]
(
	@PortalId int,
	@CrmServerID int output
)
AS
SELECT TOP 1 @CrmServerID=CrmServerID FROM adn_PortalCrmServer WHERE PortalId = @PortalId ORDER BY CrmServerId
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetCrmServerByPortal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetCrmServerByPortal]
GO

CREATE PROCEDURE [dbo].[adn_GetCrmServerByPortal]
(
	@PortalId int
)
AS
SELECT c.*,p.PortalId FROM adn_CrmServer c INNER JOIN adn_PortalCrmServer p ON c.CrmServerId = p.CrmServerId WHERE p.PortalId = @PortalId 
GO


IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_ExistCrmServersByPortal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_ExistCrmServersByPortal]
GO
CREATE PROCEDURE [dbo].[adn_ExistCrmServersByPortal]
(
	@PortalId int,
	@CountExist int output,
	@CountOther int output
)
AS
SELECT @CountExist	=	0
SELECT @CountOther	=	0
SELECT @CountOther = COUNT(CrmServerId) FROM adn_CrmServer WHERE CrmServerId NOT IN (SELECT s.CrmServerId FROM adn_PortalCrmServer s WHERE s.PortalId = @PortalId ) 
SELECT @CountExist = COUNT(CrmServerId) FROM adn_PortalCrmServer WHERE PortalId = @PortalId 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_ExistPortalsByCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_ExistPortalsByCrmServer]
GO
CREATE PROCEDURE [dbo].[adn_ExistPortalsByCrmServer]
(
	@CrmServerID int,
	@CountExist int output,
	@CountOther int output
)
AS
SELECT @CountExist	=	0
SELECT @CountOther	=	0
SELECT @CountOther = COUNT(PortalID) FROM adn_Portals WHERE PortalID NOT IN (SELECT s.PortalID FROM adn_PortalCrmServer s WHERE s.CrmServerID = @CrmServerID ) AND PortalID > -1
SELECT @CountExist = COUNT(PortalID) FROM adn_PortalCrmServer WHERE CrmServerID = @CrmServerID 
GO


IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetPortalsByCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalsByCrmServer]
GO

CREATE PROCEDURE [dbo].[adn_GetPortalsByCrmServer]
(
	@CrmServerID int
)
AS
SELECT s.CrmServerId,c.MainPortalID,p.*, CASE WHEN p.PortalId=c.MainPortalId THEN CONVERT(bit,1) ELSE CONVERT(bit,0) END AS IsMainPortal FROM adn_PortalCrmServer s INNER JOIN adn_Portals p ON s.PortalId = p.PortalID
																INNER JOIN adn_CrmServer c ON c.CrmServerId = s.CrmServerId WHERE s.CrmServerID = @CrmServerID
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddPortalCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddPortalCrmServer]
GO

CREATE PROCEDURE [dbo].[adn_AddPortalCrmServer]
(
	@PortalId int,
	@CrmServerID int,
	@IsMainPortal bit
)
AS
INSERT INTO adn_PortalCrmServer
(
	PortalId,
	CrmServerID
) 
VALUES
(
	@PortalId,
	@CrmServerID
)
IF ( @IsMainPortal = 1 )
UPDATE adn_CrmServer SET MainPortalID=@PortalId WHERE CrmServerID=@CrmServerID
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateCrmServerMainPortal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateCrmServerMainPortal]
GO

CREATE PROCEDURE [dbo].[adn_UpdateCrmServerMainPortal]
(
	@PortalId int,
	@CrmServerID int
)
AS
IF NOT EXISTS (SELECT * FROM adn_PortalCrmServer WHERE CrmServerID=@CrmServerID AND PortalId = @PortalId)
INSERT INTO adn_PortalCrmServer
(
	PortalId,
	CrmServerID
) 
VALUES
(
	@PortalId,
	@CrmServerID
)
UPDATE adn_CrmServer SET MainPortalID=@PortalId WHERE CrmServerID=@CrmServerID
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeletePortalCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeletePortalCrmServer]
GO

CREATE PROCEDURE [dbo].[adn_DeletePortalCrmServer]
(
	@PortalId int,
	@CrmServerID int
)
AS
DELETE FROM adn_PortalCrmServer WHERE PortalId = @PortalId AND CrmServerID = @CrmServerID
DECLARE @MainPortalID int
SELECT @MainPortalID=MainPortalID FROM adn_CrmServer WHERE CrmServerID=@CrmServerID
IF ( @PortalId = @MainPortalID)
UPDATE adn_CrmServer SET MainPortalID=NULL WHERE CrmServerID=@CrmServerID
GO

-- Crm Entities
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAllCrmEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllCrmEntity]
GO

CREATE PROCEDURE [dbo].[adn_GetAllCrmEntity]
AS
SELECT * FROM adn_CrmEntity 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAllCrmEntityPackages]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllCrmEntityPackages]
GO

CREATE PROCEDURE [dbo].[adn_GetAllCrmEntityPackages]
AS
SELECT DISTINCT PackageName FROM adn_CrmEntity 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_ExistCrmEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_ExistCrmEntity]
GO
CREATE PROCEDURE [dbo].[adn_ExistCrmEntity]
(
	@SchemaName [nvarchar] (128),
	@EntityVersion [nvarchar] (16),
	@Found bit output
)
AS
IF EXISTS( SELECT * FROM adn_CrmEntity WHERE SchemaName=@SchemaName AND EntityVersion=@EntityVersion )
	SELECT @Found = 1
ELSE SELECT @Found = 0
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_ExistCrmEntityByCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_ExistCrmEntityByCrmServer]
GO
CREATE PROCEDURE [dbo].[adn_ExistCrmEntityByCrmServer]
(
	@CrmServerID int,
	@CountExist int output,
	@CountOther int output
)
AS
SELECT @CountExist	=	0
SELECT @CountOther	=	0
SELECT @CountOther	=	COUNT(EntityID) FROM adn_CrmEntity WHERE EntityId NOT IN (SELECT s.EntityID FROM adn_ServerEntity s WHERE s.CrmServerID = @CrmServerID )
SELECT @CountExist	=	COUNT(EntityID) FROM adn_ServerEntity WHERE CrmServerID = @CrmServerID 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetCrmEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetCrmEntity]
GO

CREATE PROCEDURE [dbo].[adn_GetCrmEntity]
(
	@EntityId     int
)
AS
SELECT * FROM adn_CrmEntity WHERE EntityId = @EntityId
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetCrmEntityBySchemaName]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetCrmEntityBySchemaName]
GO

CREATE PROCEDURE [dbo].[adn_GetCrmEntityBySchemaName]
(
	@SchemaName [nvarchar] (128),
	@EntityVersion [nvarchar] (16)
)
AS
SELECT * FROM adn_CrmEntity WHERE SchemaName = @SchemaName AND EntityVersion LIKE @EntityVersion
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteCrmEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteCrmEntity]
GO

CREATE PROCEDURE [dbo].[adn_DeleteCrmEntity]
(
	@EntityId     int
)
AS
DELETE FROM adn_CrmEntity WHERE EntityId = @EntityId
GO


IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateCrmEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateCrmEntity]
GO

CREATE PROCEDURE [dbo].[adn_UpdateCrmEntity]
(
	@EntityId     int,
	@SchemaName [nvarchar] (128),
	@EntityVersion [nvarchar] (16),
	@FriendlyName [nvarchar] (128),
    @InitClass [nvarchar] (128),
    @LoadAssembly [nvarchar] (128),
    @PackageName [nvarchar] (50),
	@NeedCreateBuilder [bit],
	@NeedExtendBuilder [bit],
	@NeedUIBuilder [bit]
)
AS
UPDATE adn_CrmEntity set
	SchemaName			=	@SchemaName,
	EntityVersion		= 	@EntityVersion,
	FriendlyName		=	@FriendlyName,
    InitClass			=	@InitClass,
    LoadAssembly		=	@LoadAssembly,
    [PackageName]		=	@PackageName,
	NeedCreateBuilder	=	@NeedCreateBuilder,
	NeedExtendBuilder	=	@NeedExtendBuilder,
	NeedUIBuilder		=	@NeedUIBuilder
WHERE EntityId = @EntityId
GO


IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddCrmEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddCrmEntity]
GO

CREATE PROCEDURE [dbo].[adn_AddCrmEntity]
(
	@SchemaName [nvarchar] (128),
	@EntityVersion [nvarchar] (16),
	@FriendlyName [nvarchar] (128),
    @InitClass [nvarchar] (128),
    @LoadAssembly [nvarchar] (128),
    @PackageName [nvarchar] (50),
	@NeedCreateBuilder [bit],
	@NeedExtendBuilder [bit],
	@NeedUIBuilder [bit],
	@EntityId     int OUTPUT
)
AS
INSERT INTO adn_CrmEntity
(
	SchemaName,
	EntityVersion,
	FriendlyName,
    InitClass,
    LoadAssembly,
    [PackageName],
	NeedCreateBuilder,
	NeedExtendBuilder,
	NeedUIBuilder
) 
VALUES
(
	@SchemaName,
	@EntityVersion,
	@FriendlyName,
    @InitClass,
    @PackageName,
    @LoadAssembly,
	@NeedCreateBuilder,
	@NeedExtendBuilder,
	@NeedUIBuilder
)
SELECT @EntityId = @@IDENTITY
GO

-- CrmEntity ModuleGeneralDefinition
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetEntitiesByModule]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetEntitiesByModule]
GO

CREATE PROCEDURE [dbo].[adn_GetEntitiesByModule]
(
	@ModuleDefId [uniqueidentifier]
)
AS
SELECT m.*,e.* FROM adn_ModuleEntity m INNER JOIN adn_CrmEntity e ON m.EntityId = e.EntityId  WHERE ModuleDefId=@ModuleDefId
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetModulesByEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModulesByEntity]
GO

CREATE PROCEDURE [dbo].[adn_GetModulesByEntity]
(
	@EntityId     int
)
AS
SELECT m.*,g.* FROM adn_ModuleEntity m INNER JOIN adn_GeneralModuleDefinitions g ON m.ModuleDefId = g.GeneralModDefID WHERE EntityId=@EntityId
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddModuleEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddModuleEntity]
GO

CREATE PROCEDURE [dbo].[adn_AddModuleEntity]
(
	@ModuleDefId [uniqueidentifier],
	@EntityId     int
)
AS
IF EXISTS (SELECT * FROM adn_ModuleEntity WHERE ModuleDefId=@ModuleDefId AND EntityId=@EntityId )
	RETURN
INSERT INTO adn_ModuleEntity
(
	ModuleDefId,
	EntityId
) 
VALUES
(
	@ModuleDefId,
	@EntityId
)
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteModuleEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteModuleEntity]
GO

CREATE PROCEDURE [dbo].[adn_DeleteModuleEntity]
(
	@ModuleDefId [uniqueidentifier],
	@EntityId     int
)
AS
DELETE FROM adn_ModuleEntity WHERE ModuleDefId=@ModuleDefId AND EntityId=@EntityId
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_ExistModulesByCrmEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_ExistModulesByCrmEntity]
GO
CREATE PROCEDURE [dbo].[adn_ExistModulesByCrmEntity]
(
	@EntityId int,
	@CountExist int output,
	@CountOther int output
)
AS
SELECT @CountExist	=	0
SELECT @CountOther	=	0
SELECT @CountOther = COUNT(GeneralModDefID) FROM adn_GeneralModuleDefinitions  WHERE GeneralModDefID NOT IN (SELECT s.ModuleDefId FROM adn_ModuleEntity s WHERE s.EntityID = @EntityId )
SELECT @CountExist = COUNT(ModuleDefId) FROM adn_ModuleEntity WHERE EntityId = @EntityId 
GO

-- Crm Server / Entity
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_ExistCrmServerEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_ExistCrmServerEntity]
GO
CREATE PROCEDURE [dbo].[adn_ExistCrmServerEntity]
(
	@CrmServerId int,
	@EntityId int,
	@Found bit output
)
AS
IF EXISTS( SELECT * FROM adn_ServerEntity WHERE CrmServerId=@CrmServerId AND EntityId=@EntityId)
	SELECT @Found = 1
ELSE SELECT @Found = 0
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_ExistCrmServerByCrmEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_ExistCrmServerByCrmEntity]
GO
CREATE PROCEDURE [dbo].[adn_ExistCrmServerByCrmEntity]
(
	@EntityId int,
	@CountExist int output,
	@CountOther int output
)
AS
SELECT @CountExist	=	0
SELECT @CountOther	=	0
SELECT @CountOther = COUNT(CrmServerId) FROM adn_CrmServer WHERE CrmServerId NOT IN (SELECT s.CrmServerId FROM adn_ServerEntity s WHERE s.EntityID = @EntityId )
SELECT @CountExist = COUNT(CrmServerId) FROM adn_ServerEntity WHERE EntityId = @EntityId 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetEntitiesByCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetEntitiesByCrmServer]
GO
CREATE PROCEDURE [dbo].[adn_GetEntitiesByCrmServer]
(
	@CrmServerId int
)
AS
SELECT CrmServerId,s.InstalledVersion,s.InstallDate,e.* FROM adn_ServerEntity s INNER JOIN adn_CrmEntity e ON s.EntityId = e.EntityId WHERE CrmServerId=@CrmServerId 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetCrmServerEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetCrmServerEntity]
GO
CREATE PROCEDURE [dbo].[adn_GetCrmServerEntity]
(
	@CrmServerId int,
	@EntityId int
)
AS
SELECT s.CrmServerId,s.InstalledVersion,s.InstallDate,e.* FROM adn_ServerEntity s INNER JOIN adn_CrmEntity e ON s.EntityId = e.EntityId 
																				INNER JOIN adn_CrmServer c ON c.CrmServerId = s.CrmServerId 
																				WHERE s.CrmServerId=@CrmServerId 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetCrmServersByEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetCrmServersByEntity]
GO
CREATE PROCEDURE [dbo].[adn_GetCrmServersByEntity]
(
	@EntityId int
)
AS
SELECT EntityId,s.InstalledVersion,s.InstallDate,e.* FROM adn_ServerEntity s INNER JOIN adn_CrmServer e ON s.CrmServerId = e.CrmServerId WHERE EntityId=@EntityId 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddCrmServerEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddCrmServerEntity]
GO

CREATE PROCEDURE [dbo].[adn_AddCrmServerEntity]
(
	@CrmServerId int,
	@EntityId int,
	@InstalledVersion [nvarchar] (16)
)
AS
INSERT INTO adn_ServerEntity
(
	CrmServerId,
	EntityId,
	InstalledVersion,
	InstallDate
) 
VALUES
(
	@CrmServerId,
	@EntityId,
	@InstalledVersion,
	GETUTCDATE()
)
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateCrmServerEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateCrmServerEntity]
GO

CREATE PROCEDURE [dbo].[adn_UpdateCrmServerEntity]
(
	@CrmServerId int,
	@EntityId int,
	@InstalledVersion [nvarchar] (16)
)
AS
UPDATE adn_ServerEntity
	SET InstalledVersion= @InstalledVersion,InstallDate=GETUTCDATE()
WHERE CrmServerId=@CrmServerId AND EntityId=@EntityId
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteCrmServerEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteCrmServerEntity]
GO

CREATE PROCEDURE [dbo].[adn_DeleteCrmServerEntity]
(
	@CrmServerId int,
	@EntityId int
)
AS
DELETE FROM adn_ServerEntity WHERE CrmServerId=@CrmServerId AND EntityId=@EntityId
GO

-- Recycler
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_MoveModuleToNewTab]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_MoveModuleToNewTab]
GO

CREATE PROCEDURE [dbo].[adn_MoveModuleToNewTab]
(
    @ModuleID  int,
    @TabID int
)
AS
BEGIN TRAN
UPDATE adn_Modules
SET TabID = @TabID
WHERE ModuleID = @ModuleID

DELETE FROM adn_Recycler WHERE ModuleID = @ModuleID
COMMIT TRAN
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteModuleToRecycler]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteModuleToRecycler]
GO

CREATE  PROCEDURE adn_DeleteModuleToRecycler
(
    @ModuleID       int,
    @DeletedBy nvarchar(250),
    @DateDeleted datetime
)
AS
DECLARE @intErrorCode INT
DECLARE @intOldTabId INT

SELECT @intOldTabId = (SELECT TOP 1 TabID FROM adn_Modules WHERE ModuleID = @ModuleID)
--IF IT'S NOT ALREADY IN THE RECYCLER --PUT IT THERE
IF @intOldTabId <> 0  
 BEGIN  
  BEGIN TRAN
	UPDATE adn_Modules SET TabID = 0 WHERE ModuleID = @ModuleID
    SELECT @intErrorCode = @@ERROR
    IF (@intErrorCode <> 0) GOTO PROBLEM

    INSERT INTO adn_Recycler	(ModuleID, DateDeleted, DeletedBy, OriginalTab)
	VALUES	(@ModuleID, @DateDeleted, @DeletedBy, @intOldTabId)

    SELECT @intErrorCode = @@ERROR
    IF (@intErrorCode <> 0) GOTO PROBLEM
COMMIT TRAN
 END
--IT WAS ALREADY IN THE RECYCLER, AND THE USER CALLED 'DELETE' FROM THE RECYCLER MODULE
ELSE
 BEGIN
BEGIN TRAN
 	DELETE FROM adn_Modules WHERE ModuleID = @ModuleID
 	DELETE FROM adn_Recycler WHERE ModuleID = @ModuleID
COMMIT TRAN
 END


PROBLEM:
IF (@intErrorCode <> 0) BEGIN
PRINT 'Unexpected error occurred!'
    ROLLBACK TRAN
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetModuleConfigurationForIndividualModule]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleConfigurationForIndividualModule]
GO

CREATE PROCEDURE [dbo].[adn_GetModuleConfigurationForIndividualModule]
(
    @ModuleID  int
)
AS
-- Get the DataTable of module info 
SELECT TOP 1 * FROM adn_Modules INNER JOIN
	adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID INNER JOIN
	adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
WHERE (adn_Modules.ModuleID = @ModuleID)
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetPageModules]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPageModules]
GO

CREATE PROCEDURE [dbo].[adn_GetPageModules]
(
    @TabID  int
)
AS
  SELECT * FROM adn_Modules INNER JOIN
    adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID INNER JOIN
  adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
WHERE adn_Modules.TabID = @TabID
GO


IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetModulesInRecycler]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModulesInRecycler]
GO

CREATE PROCEDURE [dbo].[adn_GetModulesInRecycler]
(
 @PortalID int,
 @SortField VarChar(50)
)
AS
SELECT     
	adn_Recycler.DateDeleted, 
	adn_Recycler.DeletedBy, 
	adn_Recycler.OriginalTab, 
	adn_Recycler.ModuleID, 
	adn_Modules.ModuleTitle, 
    adn_Tabs.TabName as 'OriginalTabName'
FROM    adn_Recycler INNER JOIN
        adn_Modules ON adn_Recycler.ModuleID = adn_Modules.ModuleID INNER JOIN
        adn_Tabs ON adn_Recycler.OriginalTab = adn_Tabs.TabID
WHERE PortalID = @PortalID
ORDER BY 
	CASE 
	 WHEN @SortField = 'DateDeleted' THEN CAST(DateDeleted AS VarChar(50))
         WHEN @SortField = 'DeletedBy' THEN CAST(DeletedBy AS VarChar(50))
         WHEN @SortField = 'OriginalTab' THEN CAST(OriginalTab AS VarChar(50))
         WHEN @SortField = 'ModuleID' THEN CAST(adn_Recycler.ModuleID AS VarChar(50)) 
         WHEN @SortField = 'ModuleTitle' THEN CAST(ModuleTitle AS VarChar(50))
         WHEN @SortField = 'TabName' THEN CAST(adn_Tabs.TabName AS VarChar(50))
         ELSE ModuleTitle
     END
GO


IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAuthDeleteRolesRecycler]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAuthDeleteRolesRecycler]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAuthViewRolesRecycler]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAuthViewRolesRecycler]
GO

CREATE  PROCEDURE adn_GetAuthDeleteRolesRecycler
(
    @PortalID    int,
    @ModuleID    int,
    @AccessRoles nvarchar (512) OUTPUT,
    @DeleteRoles   nvarchar (512) OUTPUT
)
AS
SELECT  
    @AccessRoles = adn_Tabs.AuthorizedRoles,
    @DeleteRoles   = adn_Modules.AuthorizedDeleteRoles
FROM adn_Modules
  INNER JOIN adn_Recycler ON adn_Modules.ModuleID = adn_Recycler.ModuleID
  INNER JOIN adn_Tabs ON adn_Recycler.OriginalTab = adn_Tabs.TabID
WHERE adn_Modules.ModuleID = @ModuleID AND adn_Tabs.PortalID = @PortalID
GO

CREATE  PROCEDURE adn_GetAuthViewRolesRecycler
(
    @PortalID    int,
    @ModuleID    int,
    @AccessRoles nvarchar (512) OUTPUT,
    @ViewRoles   nvarchar (512) OUTPUT
)
AS
SELECT  
    @AccessRoles = adn_Tabs.AuthorizedRoles,
    @ViewRoles   = adn_Modules.AuthorizedViewRoles
FROM adn_Modules 
INNER JOIN adn_Recycler ON adn_Modules.ModuleID = adn_Recycler.ModuleID 
INNER JOIN adn_Tabs ON adn_Recycler.OriginalTab = adn_Tabs.TabID    
WHERE adn_Modules.ModuleID = @ModuleID
  AND adn_Tabs.PortalID = @PortalID
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetModuleUserSettings]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleUserSettings]
GO

CREATE  PROCEDURE adn_GetModuleUserSettings
(
    @ModuleID int,
    @UserID uniqueidentifier
)
AS
SELECT * FROM adn_ModuleUserSettings
WHERE (ModuleID = @ModuleID AND UserID = @UserID)
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetModuleUserSettingsGroup]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleUserSettingsGroup]
GO

CREATE  PROCEDURE adn_GetModuleUserSettingsGroup
(
    @ModuleID int,
    @UserID uniqueidentifier,
    @SettingGroup int
)
AS
SELECT * FROM adn_ModuleUserSettings
WHERE (ModuleID = @ModuleID AND UserID = @UserID AND SettingGroup = @SettingGroup)
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateModuleUserSetting]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateModuleUserSetting]
GO

CREATE  PROCEDURE adn_UpdateModuleUserSetting
(
    @ModuleID      int,
    @UserID 	   uniqueidentifier,
    @SettingName   nvarchar(50),
    @SettingValue  nvarchar(1500),
    @SettingGroup  int
)
AS
IF NOT EXISTS (
    SELECT * FROM adn_ModuleUserSettings 
    WHERE ModuleID = @ModuleID
      AND UserID = @UserID
      AND SettingName = @SettingName
)
INSERT INTO adn_ModuleUserSettings (
    ModuleID,
    UserID,
    SettingName,
    SettingValue,
    SettingGroup
) 
VALUES (
    @ModuleID,
    @UserID,
    @SettingName,
    @SettingValue,
    @SettingGroup
)
ELSE
UPDATE adn_ModuleUserSettings
SET SettingValue = @SettingValue,
    SettingGroup = @SettingGroup
WHERE ModuleID = @ModuleID
  AND UserID = @UserID
  AND SettingName = @SettingName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_AddGeneralModuleDefinitions]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddGeneralModuleDefinitions]
GO

CREATE PROCEDURE [dbo].[adn_AddGeneralModuleDefinitions]
	@GeneralModDefID uniqueidentifier,
	@FriendlyName nvarchar(128),
	@DesktopSrc nvarchar(256),
	@AssemblyName varchar(50),
	@ClassName nvarchar(128),
	@Category nvarchar(128),
	@Usage nvarchar(1024),
	@VersionType int,
	@Admin bit
AS
IF EXISTS (SELECT * FROM adn_GeneralModuleDefinitions WHERE GeneralModDefID = @GeneralModDefID)
UPDATE adn_GeneralModuleDefinitions
SET
	FriendlyName	=	@FriendlyName,
	DesktopSrc		=	@DesktopSrc,
	Usage			=	@Usage,
	AssemblyName	=	@AssemblyName,
	ClassName		=	@ClassName,
	Category		=	@Category,
	VersionType		=	@VersionType,
	Admin			=	@Admin
WHERE
	GeneralModDefID =	@GeneralModDefID
ELSE
INSERT INTO adn_GeneralModuleDefinitions
(
	GeneralModDefID,
	FriendlyName,
	DesktopSrc,
	Usage,
	AssemblyName,
	ClassName,
	Category,
	VersionType,
	Admin
)
VALUES
(
	@GeneralModDefID,
	@FriendlyName,
	@DesktopSrc,
	@Usage,
	@AssemblyName,
	@ClassName,
	@Category,
	@VersionType,
	@Admin
)
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateGeneralModuleDefinitions]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateGeneralModuleDefinitions]
GO

CREATE PROCEDURE [dbo].[adn_UpdateGeneralModuleDefinitions]
	@GeneralModDefID uniqueidentifier,
	@FriendlyName nvarchar(128),
	@DesktopSrc nvarchar(256),
	@AssemblyName nvarchar(50),
	@Usage nvarchar(1024),
	@ClassName nvarchar(128),
	@Category  nvarchar(128),
	@VersionType int,
	@Admin bit
AS
UPDATE adn_GeneralModuleDefinitions
SET
	FriendlyName	=	@FriendlyName,
	DesktopSrc		=	@DesktopSrc,
	AssemblyName	=	@AssemblyName,
	Usage			=	@Usage,
	ClassName		=	@ClassName,
	Category		=	@Category,
    VersionType		=	@VersionType,
	[Admin]			=	@Admin
WHERE
	GeneralModDefID =	@GeneralModDefID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_AddModule]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddModule]
GO

CREATE PROCEDURE [dbo].[adn_AddModule]
(
    @TabID                  int,
    @ModuleOrder            int,
    @ModuleSettingsID       int,
    @ModuleTitle            nvarchar(256),
    @PaneName               nvarchar(50),
    @ModuleDefID            int,
    @CacheTime              int,
    @EditRoles              nvarchar(512),
    @AddRoles               nvarchar(512),
    @ViewRoles              nvarchar(512),
    @DeleteRoles            nvarchar(512),
    @PropertiesRoles	    nvarchar(512),
    @MoveModuleRoles	    nvarchar(512),
    @DeleteModuleRoles	    nvarchar(512),
    @ShowEveryWhere         bit,
    @SupportCollapsable     bit,
    @ModuleID               int OUTPUT
)
AS
INSERT INTO adn_Modules
(
    TabID,
    ModuleOrder,
    ModuleSettingsID,
    ModuleTitle,
    PaneName,
    ModuleDefID,
    CacheTime,
    AuthorizedEditRoles,
    AuthorizedAddRoles,
    AuthorizedViewRoles,
    AuthorizedDeleteRoles,
    AuthorizedPropertiesRoles,
    AuthorizedMoveModuleRoles,
    AuthorizedDeleteModuleRoles,
    NewVersion, 
    SupportCollapsable,
    ShowEveryWhere    
) 
VALUES
(
    @TabID,
    @ModuleOrder,
    @ModuleSettingsID,
    @ModuleTitle,
    @PaneName,
    @ModuleDefID,
    @CacheTime,
    @EditRoles,
    @AddRoles,
    @ViewRoles,
    @DeleteRoles,
    @PropertiesRoles,
    @MoveModuleRoles,
    @DeleteModuleRoles,
    1, 
    @SupportCollapsable,
    @ShowEveryWhere  
)
SELECT @ModuleID = @@IDENTITY
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeleteModule]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteModule]
GO

CREATE PROCEDURE [dbo].[adn_DeleteModule]
(
    @ModuleID       int
)
AS
DELETE FROM adn_Modules WHERE ModuleID = @ModuleID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeleteModuleDefinition]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteModuleDefinition]
GO

CREATE PROCEDURE [dbo].[adn_DeleteModuleDefinition]
(
    @ModuleDefID uniqueidentifier
)
AS
DELETE FROM adn_GeneralModuleDefinitions WHERE GeneralModDefID = @ModuleDefID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateModuleDefinitions]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateModuleDefinitions]
GO
-- DO NOT allow changing a module registered with admin portal (-2)
CREATE PROCEDURE [dbo].[adn_UpdateModuleDefinitions]
(
    @GeneralModDefID	uniqueidentifier,
    @PortalID			int = -100,
    @ischecked			bit
)
AS
IF EXISTS (SELECT 1 FROM adn_ModuleDefinitions WHERE (GeneralModDefID = @GeneralModDefID) AND ( PortalID = -2) )
	RETURN
IF (@PortalID = -100)
BEGIN
	IF (@ischecked = 0)
			DELETE FROM adn_ModuleDefinitions WHERE adn_ModuleDefinitions.GeneralModDefID = @GeneralModDefID
			AND adn_ModuleDefinitions.ModuleDefID NOT IN (SELECT ModuleDefID FROM adn_Modules) -- module is not in use
	ELSE 
	INSERT INTO adn_ModuleDefinitions (PortalID, GeneralModDefID)
	(
		SELECT adn_Portals.PortalID, adn_GeneralModuleDefinitions.GeneralModDefID
		FROM   adn_Portals CROSS JOIN adn_GeneralModuleDefinitions
		WHERE adn_GeneralModuleDefinitions.GeneralModDefID = @GeneralModDefID 
          AND PortalID >= 0
          AND adn_Portals.PortalID NOT IN (SELECT PortalID FROM adn_ModuleDefinitions WHERE adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID)
	)
END
ELSE --PortalID <> -100
BEGIN
IF (@ischecked = 0)
	DELETE FROM adn_ModuleDefinitions WHERE adn_ModuleDefinitions.GeneralModDefID = @GeneralModDefID AND PortalID = @PortalID
ELSE
	IF NOT EXISTS (SELECT ModuleDefID FROM adn_ModuleDefinitions WHERE GeneralModDefID = @GeneralModDefID AND PortalID = @PortalID  )
	BEGIN
		INSERT INTO adn_ModuleDefinitions(PortalID,GeneralModDefID) VALUES (@PortalID,@GeneralModDefID)
	END
END
GO

-- portal

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_AddPortal2]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddPortal2]
GO

CREATE PROCEDURE [dbo].[adn_AddPortal2]
(
    @PortalAlias            nvarchar(128),
    @PortalName             nvarchar(128),
    @PortalPath             nvarchar(128),
    @PortalType             int,
    @PortalID               int OUTPUT
)
AS
INSERT INTO adn_Portals (PortalAlias,PortalName,PortalPath,PortalType)
	VALUES (@PortalAlias,@PortalName,@PortalPath,@PortalType)
SELECT @PortalID = @@IDENTITY
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdatePortal2]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdatePortal2]
GO

CREATE PROCEDURE [dbo].[adn_UpdatePortal2]
(
    @PortalID           int,
    @PortalName         nvarchar(128),
    @PortalPath         nvarchar(128),
    @PortalType         int
)
AS
UPDATE adn_Portals
SET PortalName = @PortalName,
    PortalPath = @PortalPath,
	PortalType = @PortalType
WHERE PortalID = @PortalID
GO

-- delete old version if present
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortalSettingsPortalID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalSettingsPortalID]
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortalByPortalID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalByPortalID]
GO

CREATE PROCEDURE [dbo].[adn_GetPortalByPortalID]
(
    @PortalID   int
)
AS
SELECT * FROM adn_Portals WHERE (PortalID = @PortalID)
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortalCrmServer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalCrmServer]
GO

CREATE PROCEDURE [dbo].[adn_GetPortalCrmServer]
(
    @PortalID   int
)
AS
SELECT s.*,c.* FROM adn_Portals p LEFT OUTER JOIN adn_PortalCrmServer s ON p.PortalId = s.PortalID LEFT OUTER JOIN adn_CrmServer c ON s.CrmServerId = c.CrmServerId
	WHERE (p.PortalID = @PortalID)
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortals]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortals]
GO

CREATE PROCEDURE [dbo].[adn_GetPortals]
AS
SELECT * FROM adn_Portals WHERE ( PortalID > -1 )
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeletePortal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeletePortal]
GO

CREATE PROCEDURE [dbo].[adn_DeletePortal]
(
    @PortalID       int
)
AS
IF ( @PortalID < 0 ) RETURN
DELETE FROM adn_Tabs WHERE PortalID = @PortalID
DELETE FROM adn_PortalAlias WHERE PortalID = @PortalID
DELETE FROM adn_Portals WHERE PortalID = @PortalID
GO

-- portal settings
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortalSingleCustomSettingsByAlias]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalSingleCustomSettingsByAlias]
GO
CREATE PROCEDURE [dbo].[adn_GetPortalSingleCustomSettingsByAlias]
(
    @PortalAlias	nvarchar(50),
    @SettingName nvarchar(50),
    @SettingValue nvarchar(1500) OUTPUT
)
AS
DECLARE @PortalID int;
-- First get portalid from alias 
EXEC @PortalId= adn_GetPortalFromAlias @PortalAlias
IF @PortalID = -1 RETURN
SELECT @SettingValue=SettingValue FROM adn_PortalSettings WHERE PortalID = @PortalID AND SettingName=@SettingName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortalSingleCustomSettings]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalSingleCustomSettings]
GO
CREATE PROCEDURE [dbo].[adn_GetPortalSingleCustomSettings]
(
	@PortalID int,
    @SettingName nvarchar(50),
    @SettingValue nvarchar(1500) OUTPUT
)
AS
SELECT @SettingValue=SettingValue FROM adn_PortalSettings WHERE PortalID = @PortalID AND SettingName=@SettingName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortalCustomSettings]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalCustomSettings]
GO

CREATE PROCEDURE [dbo].[adn_GetPortalCustomSettings]
(
    @PortalID int
)
AS
SELECT SettingName, SettingValue FROM adn_PortalSettings WHERE PortalID = @PortalID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdatePortalSetting]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdatePortalSetting]
GO

CREATE PROCEDURE [dbo].[adn_UpdatePortalSetting]
(
    @PortalID      int,
    @SettingName   nvarchar(50),
    @SettingValue  nvarchar(1500)
)
AS
IF NOT EXISTS ( SELECT * FROM adn_PortalSettings WHERE PortalID = @PortalID AND SettingName = @SettingName )
	INSERT INTO adn_PortalSettings (PortalID,SettingName,SettingValue) VALUES (@PortalID,@SettingName,@SettingValue)
ELSE
	UPDATE adn_PortalSettings SET SettingValue = @SettingValue WHERE PortalID = @PortalID AND SettingName = @SettingName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortalFromAlias]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalFromAlias]
GO

CREATE PROCEDURE [dbo].[adn_GetPortalFromAlias]
(
    @PortalAlias            nvarchar(128)
)
AS
DECLARE @PortalID int;
SET @PortalID	=	-1;
SET @PortalID	= (SELECT PortalID FROM adn_Portals WHERE PortalAlias = @PortalAlias )
IF NOT @PortalID IS NULL
	RETURN @PortalID
SET @PortalID	= ( SELECT a.PortalID FROM adn_PortalAlias a LEFT OUTER JOIN adn_Portals p ON a.PortalID = p.PortalID WHERE a.PortalAlias = @PortalAlias )
IF NOT @PortalID IS NULL
	RETURN @PortalID
RETURN -1
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetBaseAlias]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetBaseAlias]
GO

CREATE PROCEDURE [dbo].[adn_GetBaseAlias]
(
    @PortalAlias            nvarchar(128),
    @BaseAlias				nvarchar(128) output
)
AS
DECLARE @PortalID int;
EXEC @PortalId			=	adn_GetPortalFromAlias @PortalAlias
IF @PortalID = -1 RETURN
-- the real tab portal 
SELECT @BaseAlias		=	PortalAlias	FROM adn_portals WHERE PortalID = @PortalID 
GO

-- portal alias
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_AddPortalAlias]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddPortalAlias]
GO

CREATE PROCEDURE [dbo].[adn_AddPortalAlias]
(
    @PortalID               int,
    @PortalAlias            nvarchar(128)
)
AS
IF NOT EXISTS ( SELECT * FROM adn_Portals WHERE PortalAlias = @PortalAlias )
	INSERT INTO adn_PortalAlias (PortalID,PortalAlias) VALUES (@PortalID,@PortalAlias)
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdatePortalAlias]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdatePortalAlias]
GO

CREATE PROCEDURE [dbo].[adn_UpdatePortalAlias]
(
    @PortalID           int,
    @OldPortalAlias      nvarchar(128),
    @PortalAlias         nvarchar(128)
)
AS
UPDATE adn_PortalAlias SET PortalAlias = @PortalAlias  WHERE PortalID = @PortalID AND PortalAlias = @OldPortalAlias
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortalAlias]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalAlias]
GO

CREATE PROCEDURE [dbo].[adn_GetPortalAlias]
(
    @PortalID           int
)
AS
SELECT * FROM adn_PortalAlias WHERE PortalID = @PortalID 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeletePortalAlias]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeletePortalAlias]
GO

CREATE PROCEDURE [dbo].[adn_DeletePortalAlias]
(
    @PortalID           int,
    @PortalAlias         nvarchar(128)
)
AS
DELETE FROM adn_PortalAlias WHERE PortalID = @PortalID AND PortalAlias = @PortalAlias
GO

--  DB version
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetCurrentDbVersion]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetCurrentDbVersion]
GO

CREATE PROCEDURE [dbo].[adn_GetCurrentDbVersion]
AS
SELECT TOP 1 Release FROM adn_Versions ORDER BY Release DESC
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAllDbVersions]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllDbVersions]
GO

CREATE PROCEDURE [dbo].[adn_GetAllDbVersions]
AS
SELECT * FROM adn_Versions ORDER BY Release DESC
GO

-- Packages

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_CreatePageAndModule2]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_CreatePageAndModule2]
GO

CREATE PROCEDURE [dbo].[adn_CreatePageAndModule2]
(
	@PortalId int,
	@ParentTab int,
	@PageTitle nvarchar(256),
    @ModuleTitle nvarchar(256),
    @ModuleDefGuid uniqueidentifier,
	@ModuleID int OUTPUT, 
    @newTabId int OUTPUT
)
AS
DECLARE @DBAllUser nvarchar(512) 
SELECT @DBAllUser = 'All Users'
DECLARE @DBAdmin2 nvarchar(512) 
SELECT @DBAdmin2 = 'Admins;'

IF NOT EXISTS (SELECT * FROM adn_Tabs WHERE TabName = @PageTitle AND ParentTabId = @ParentTab AND PortalID = @PortalId )
BEGIN
EXEC adn_AddTab @PortalId,@ParentTab,@PageTitle,'DefaultSkin', 100,3,0,0,0,0,0,@DBAllUser,@newTabId OUTPUT
DECLARE @GenModuleID int 
EXEC adn_GetModuleDefinitionByGuid @PortalId,@ModuleDefGuid,@GenModuleID OUTPUT
EXEC adn_AddModule @newTabId,1,0,@ModuleTitle,'contentpane',@GenModuleID, 0,
         @DBAdmin2, @DBAdmin2, @DBAdmin2, @DBAdmin2, @DBAdmin2, @DBAdmin2, @DBAdmin2,0,0,@ModuleID OUTPUT
END
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_CreatePageAndModule]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_CreatePageAndModule]
GO

CREATE PROCEDURE [dbo].[adn_CreatePageAndModule]
(
	@ParentTab int,
	@PageTitle nvarchar(256),
    @ModuleTitle nvarchar(256),
    @ModuleDefGuid uniqueidentifier,
	@ModuleID int OUTPUT, 
    @newTabId int OUTPUT
)
AS
DECLARE @DBAllUser nvarchar(512) 
SELECT @DBAllUser = 'All Users'
DECLARE @DBAdmin2 nvarchar(512) 
SELECT @DBAdmin2 = 'Admins;'

IF NOT EXISTS (SELECT * FROM adn_Tabs WHERE TabName = @PageTitle AND ParentTabId = @ParentTab AND PortalID = 0 )
BEGIN
EXEC adn_AddTab 0,@ParentTab,@PageTitle,'DefaultSkin', 100,3,0,0,0,0,0,@DBAllUser,@newTabId OUTPUT
DECLARE @GenModuleID int 
EXEC adn_GetModuleDefinitionByGuid 0,@ModuleDefGuid,@GenModuleID OUTPUT
EXEC adn_AddModule @newTabId,1,0,@ModuleTitle,'contentpane',@GenModuleID, 0,
         @DBAdmin2, @DBAdmin2, @DBAdmin2, @DBAdmin2, @DBAdmin2, @DBAdmin2, @DBAdmin2,0,0,@ModuleID OUTPUT
END
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetCurrentPackage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetCurrentPackage]
GO

CREATE PROCEDURE [dbo].[adn_GetCurrentPackage]
(
    @PackageName  nvarchar(50)
)
AS
SELECT TOP 1 * FROM adn_Packages WHERE [PackageName]=@PackageName ORDER BY Release, Version DESC
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPackage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPackage]
GO

CREATE PROCEDURE [dbo].[adn_GetPackage]
(
    @PackageName  nvarchar(50)
)
AS
SELECT * FROM adn_Packages WHERE [PackageName]=@PackageName ORDER BY Release,Version DESC
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_AddPackage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddPackage]
GO

CREATE PROCEDURE [dbo].[adn_AddPackage]
(	
@PackageName [nvarchar] (50),
@Release [int],
@Version [nvarchar] (50),
@ReleaseDate [datetime] 
)
AS
INSERT INTO adn_Packages (PackageName,Release,Version,ReleaseDate) VALUES (@PackageName,@Release,@Version,@ReleaseDate)
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAllPackages]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllPackages]
GO

CREATE PROCEDURE [dbo].[adn_GetAllPackages]
AS
SELECT * FROM adn_Packages ORDER BY [PackageName],Release,Version DESC
GO

-- modules definitions
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetCurrentModuleDefinitions]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetCurrentModuleDefinitions]
GO

CREATE PROCEDURE [dbo].[adn_GetCurrentModuleDefinitions]
(
    @PortalID  int
)
AS
SELECT adn_GeneralModuleDefinitions.FriendlyName,
    adn_GeneralModuleDefinitions.DesktopSrc,
    adn_GeneralModuleDefinitions.Usage,
    adn_GeneralModuleDefinitions.Admin,
    adn_GeneralModuleDefinitions.Lock,
    adn_GeneralModuleDefinitions.VersionType,
    adn_GeneralModuleDefinitions.Category,
    adn_GeneralModuleDefinitions.GeneralModDefID,
    adn_ModuleDefinitions.ModuleDefID
FROM adn_ModuleDefinitions INNER JOIN adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
WHERE ((adn_ModuleDefinitions.PortalID = @PortalID) OR (adn_ModuleDefinitions.PortalID = -2)) AND (adn_GeneralModuleDefinitions.VersionType >= 0)
ORDER BY adn_GeneralModuleDefinitions.Admin, adn_GeneralModuleDefinitions.Category,adn_GeneralModuleDefinitions.FriendlyName
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModuleDefinitions]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleDefinitions]
GO

CREATE PROCEDURE [dbo].[adn_GetModuleDefinitions]
AS
SELECT GeneralModDefID, FriendlyName, DesktopSrc,Usage,VersionType,[Admin],[Lock],Category
FROM adn_GeneralModuleDefinitions WHERE (VersionType >= 0) ORDER BY [Admin], FriendlyName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModuleDefinitionsLock]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleDefinitionsLock]
GO

CREATE PROCEDURE [dbo].[adn_GetModuleDefinitionsLock]
(
	@GeneralModDefID uniqueidentifier
)
AS
SELECT [Lock] FROM adn_GeneralModuleDefinitions WHERE GeneralModDefID = @GeneralModDefID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_SwitchModuleDefinitionsLock]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_SwitchModuleDefinitionsLock]
GO

CREATE PROCEDURE [dbo].[adn_SwitchModuleDefinitionsLock]
(
	@GeneralModDefID uniqueidentifier
)
AS
UPDATE adn_GeneralModuleDefinitions 
	SET [Lock]  = CASE WHEN [Lock] = 0 THEN 1 ELSE 0 END
WHERE GeneralModDefID = @GeneralModDefID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetCurrentModuleDefinitionsByCategory]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetCurrentModuleDefinitionsByCategory]
GO

CREATE PROCEDURE [dbo].[adn_GetCurrentModuleDefinitionsByCategory]
(
    @PortalID  int,
    @Category nvarchar(128)
)
AS
SELECT adn_GeneralModuleDefinitions.FriendlyName,
    adn_GeneralModuleDefinitions.DesktopSrc,
    adn_GeneralModuleDefinitions.Usage,
    adn_GeneralModuleDefinitions.Admin,
    adn_GeneralModuleDefinitions.Lock,
    adn_GeneralModuleDefinitions.VersionType,
    adn_GeneralModuleDefinitions.Category,
    adn_GeneralModuleDefinitions.GeneralModDefID,
    adn_ModuleDefinitions.ModuleDefID
FROM adn_ModuleDefinitions INNER JOIN adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
WHERE (((adn_ModuleDefinitions.PortalID = @PortalID) OR (adn_ModuleDefinitions.PortalID = -2))) AND (adn_GeneralModuleDefinitions.Category = @Category) AND (adn_GeneralModuleDefinitions.VersionType >= 0)
ORDER BY adn_GeneralModuleDefinitions.Admin, adn_GeneralModuleDefinitions.FriendlyName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetCurrentModuleCategories]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetCurrentModuleCategories]
GO

CREATE PROCEDURE [dbo].[adn_GetCurrentModuleCategories]
(
    @PortalID  int
)
AS
SELECT DISTINCT adn_GeneralModuleDefinitions.Category
FROM adn_ModuleDefinitions INNER JOIN adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
WHERE (adn_ModuleDefinitions.PortalID = @PortalID) OR (adn_ModuleDefinitions.PortalID = -2)
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetGeneralModuleDefinitionByName]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetGeneralModuleDefinitionByName]
GO

CREATE PROCEDURE [dbo].[adn_GetGeneralModuleDefinitionByName]
(
	@FriendlyName nvarchar(128),
	@ModuleID uniqueidentifier OUTPUT
)
AS
SELECT @ModuleID =( SELECT  adn_GeneralModuleDefinitions.GeneralModDefID FROM adn_GeneralModuleDefinitions 
						WHERE (adn_GeneralModuleDefinitions.FriendlyName = @FriendlyName))
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetLastModified]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetLastModified]
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModuleDefinitionByID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleDefinitionByID]
GO

CREATE PROCEDURE [dbo].[adn_GetModuleDefinitionByID]
(
	@ModuleID int
)
AS
SELECT adn_ModuleDefinitions.ModuleDefID, 
	adn_ModuleDefinitions.PortalID, 
	adn_GeneralModuleDefinitions.FriendlyName, 
	adn_GeneralModuleDefinitions.DesktopSrc, 
	adn_GeneralModuleDefinitions.Usage,
	adn_GeneralModuleDefinitions.VersionType,
	adn_GeneralModuleDefinitions.Category,	
    adn_GeneralModuleDefinitions.Admin, 
    adn_Modules.ModuleID
FROM adn_GeneralModuleDefinitions INNER JOIN
      adn_ModuleDefinitions ON adn_GeneralModuleDefinitions.GeneralModDefID = adn_ModuleDefinitions.GeneralModDefID INNER JOIN
      adn_Modules ON adn_ModuleDefinitions.ModuleDefID = adn_Modules.ModuleDefID
WHERE (adn_Modules.ModuleID = @ModuleID) AND (adn_GeneralModuleDefinitions.VersionType >= 0)
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModuleDefinitionByName]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleDefinitionByName]
GO

CREATE PROCEDURE [dbo].[adn_GetModuleDefinitionByName]
(
	@PortalID int,
	@FriendlyName nvarchar(128),
	@ModuleID int OUTPUT
)
AS

SELECT
    @ModuleID = (   SELECT adn_ModuleDefinitions.ModuleDefID
    FROM adn_GeneralModuleDefinitions LEFT JOIN
         adn_ModuleDefinitions ON adn_GeneralModuleDefinitions.GeneralModDefID = adn_ModuleDefinitions.GeneralModDefID
    WHERE (adn_ModuleDefinitions.PortalID = @PortalID) AND (adn_GeneralModuleDefinitions.FriendlyName = @FriendlyName))
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModuleDefinitionByGuid]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleDefinitionByGuid]
GO

CREATE PROCEDURE [dbo].[adn_GetModuleDefinitionByGuid]
(
	@PortalID int,
	@Guid uniqueidentifier,
	@ModuleID int OUTPUT
)
AS
SELECT @ModuleID =(   SELECT adn_ModuleDefinitions.ModuleDefID
				FROM adn_GeneralModuleDefinitions LEFT OUTER JOIN
					 adn_ModuleDefinitions ON adn_GeneralModuleDefinitions.GeneralModDefID = adn_ModuleDefinitions.GeneralModDefID
				WHERE (adn_ModuleDefinitions.PortalID = @PortalID) AND (adn_ModuleDefinitions.GeneralModDefID = @Guid))
IF (@ModuleID IS NULL )
	SELECT @ModuleID =(   SELECT adn_ModuleDefinitions.ModuleDefID
				FROM adn_GeneralModuleDefinitions LEFT OUTER JOIN
					 adn_ModuleDefinitions ON adn_GeneralModuleDefinitions.GeneralModDefID = adn_ModuleDefinitions.GeneralModDefID
				WHERE (adn_ModuleDefinitions.PortalID = -2) AND (adn_ModuleDefinitions.GeneralModDefID = @Guid))
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModuleDefinitionsByDefId]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleDefinitionsByDefId]
GO

CREATE PROCEDURE [dbo].[adn_GetModuleDefinitionsByDefId]
(
	@ModuleDefID int
)
AS
SELECT gd.*,md.portalID FROM adn_Moduledefinitions md LEFT OUTER JOIN adn_GeneralModuleDefinitions gd ON md.GeneralModDefID = gd.GeneralModDefID
WHERE ModuleDefID = @ModuleDefID
GO

-- modules
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModulesByDefId]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModulesByDefId]
GO

CREATE PROCEDURE [dbo].[adn_GetModulesByDefId]
(
	@ModuleDefID int
)
AS
SELECT adn_Modules.ModuleID FROM adn_Modules WHERE adn_Modules.ModuleDefID = @ModuleDefID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetFirstModuleByDefId]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFirstModuleByDefId]
GO

CREATE PROCEDURE [dbo].[adn_GetFirstModuleByDefId]
(
	@ModuleDefID int
)
AS
DECLARE @ret int
SELECT TOP 1 @ret=adn_Modules.ModuleID FROM adn_Modules WHERE adn_Modules.ModuleDefID = @ModuleDefID
RETURN @ret
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetGuid]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetGuid]
GO

CREATE PROCEDURE [dbo].[adn_GetGuid]
(
    @ModuleID int
) 
AS 
SELECT adn_ModuleDefinitions.GeneralModDefID
FROM adn_GeneralModuleDefinitions INNER JOIN
     adn_ModuleDefinitions ON adn_GeneralModuleDefinitions.GeneralModDefID = adn_ModuleDefinitions.GeneralModDefID INNER JOIN
     adn_Modules ON adn_ModuleDefinitions.ModuleDefID = adn_Modules.ModuleDefID
WHERE (adn_Modules.ModuleID = @ModuleID)
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModuleInUse]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleInUse]
GO

CREATE PROCEDURE [dbo].[adn_GetModuleInUse]
(
    @ModuleID uniqueidentifier
)
AS
SELECT adn_Portals.PortalID, adn_Portals.PortalAlias, adn_Portals.PortalName, '1' AS Checked
FROM adn_Portals LEFT OUTER JOIN adn_ModuleDefinitions ON adn_Portals.PortalID = adn_ModuleDefinitions.PortalID
WHERE adn_ModuleDefinitions.GeneralModDefID = @ModuleID
UNION
SELECT DISTINCT PortalID, PortalAlias, PortalName, '0' AS Checked FROM adn_Portals
WHERE PortalID NOT IN (SELECT adn_Portals.PortalID
     FROM adn_Portals LEFT OUTER JOIN adn_ModuleDefinitions ON adn_Portals.PortalID = adn_ModuleDefinitions.PortalID
     WHERE adn_ModuleDefinitions.GeneralModDefID = @ModuleID )
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModulesAllPortals]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModulesAllPortals]
GO

--Fix on ShortuctAll module, shortcuts should not be displayed on adn_GetModulesAllPortals list
CREATE PROCEDURE [dbo].[adn_GetModulesAllPortals]
AS
SELECT adn_Modules.ModuleID, adn_Portals.PortalAlias + '/' + adn_Tabs.TabName + '/' + adn_Modules.ModuleTitle + ' (' + adn_GeneralModuleDefinitions.FriendlyName + ')'  AS ModuleTitle, PortalAlias, adn_Tabs.TabOrder
FROM adn_Modules INNER JOIN
  adn_Tabs ON adn_Modules.TabID = adn_Tabs.TabID INNER JOIN
  adn_Portals ON adn_Tabs.PortalID = adn_Portals.PortalID INNER JOIN
  adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID INNER JOIN
  adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
WHERE     (adn_Modules.ModuleID > 0) 
AND (adn_GeneralModuleDefinitions.Admin = 0) 
AND (adn_GeneralModuleDefinitions.Lock = 0) 
AND (adn_GeneralModuleDefinitions.GeneralModDefID <> '23259716-3955-4f19-AB3F-503F99F63171' AND 
    adn_GeneralModuleDefinitions.GeneralModDefID <> 'B47BC165-91A2-4970-ADC5-5A3B727469E3')
ORDER BY PortalAlias, adn_Modules.ModuleTitle
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModulesByName]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModulesByName]
GO

CREATE PROCEDURE [dbo].[adn_GetModulesByName]
(
	@ModuleName varchar(128),
	@PortalID int
)
AS
SELECT adn_Modules.ModuleID, adn_Modules.ModuleTitle
FROM adn_GeneralModuleDefinitions INNER JOIN
  adn_ModuleDefinitions ON adn_GeneralModuleDefinitions.GeneralModDefID = adn_ModuleDefinitions.GeneralModDefID INNER JOIN
  adn_Modules ON adn_ModuleDefinitions.ModuleDefID = adn_Modules.ModuleDefID
WHERE (adn_ModuleDefinitions.PortalID = @PortalID) AND (adn_GeneralModuleDefinitions.FriendlyName = @ModuleName)
ORDER BY adn_Modules.ModuleTitle
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModuleSettings]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleSettings]
GO

CREATE PROCEDURE [dbo].[adn_GetModuleSettings]
(
    @ModuleID int
)
AS
SELECT * FROM adn_ModuleSettings WHERE ModuleID = @ModuleID ORDER BY SettingGroup
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModuleSettingsGroup]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleSettingsGroup]
GO

CREATE PROCEDURE [dbo].[adn_GetModuleSettingsGroup]
(
    @ModuleID int,
    @SettingGroup int
)
AS
SELECT * FROM adn_ModuleSettings WHERE (ModuleID = @ModuleID) AND SettingGroup = @SettingGroup
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModulesSinglePortal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModulesSinglePortal]
GO

CREATE PROCEDURE [dbo].[adn_GetModulesSinglePortal]
(
    @PortalID  int
)
AS
SELECT adn_Modules.ModuleID, adn_Tabs.TabName + '/' + adn_Modules.ModuleTitle + ' (' + adn_GeneralModuleDefinitions.FriendlyName + ')' AS ModTitle, adn_Tabs.TabOrder
FROM adn_Modules INNER JOIN
     adn_Tabs ON adn_Modules.TabID = adn_Tabs.TabID INNER JOIN
     adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID INNER JOIN
     adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
WHERE (adn_Tabs.PortalID = @PortalID) 
AND (adn_GeneralModuleDefinitions.Admin = 0) 
AND (adn_GeneralModuleDefinitions.Lock = 0) 
AND (adn_GeneralModuleDefinitions.GeneralModDefID <> '23259716-3955-4f19-AB3F-503F99F63171' 
	AND 
	adn_GeneralModuleDefinitions.GeneralModDefID <> 'B47BC165-91A2-4970-ADC5-5A3B727469E3')
ORDER BY TabOrder, adn_Modules.ModuleTitle
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortalSettings]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalSettings]
GO

CREATE PROCEDURE [dbo].[adn_GetPortalSettings]
(
    @PortalAlias	nvarchar(128),
    @TabID			int OUTPUT,
    @PortalLanguage nvarchar(12),
    @PortalID		int OUTPUT,
    @PortalName		nvarchar(128) OUTPUT,
    @BaseAlias		nvarchar(128) OUTPUT,
    @PortalPath		nvarchar(128) OUTPUT,
    @PortalType     int OUTPUT,
    @TabName		nvarchar (50)  OUTPUT,
	@PageTitle		nvarchar (200)  OUTPUT,
    @PageKeyPhrase	nvarchar (50)  OUTPUT,
    @UrlName		nvarchar (50)  OUTPUT,
    @TabSkinID		nvarchar (50)  OUTPUT,
    @TabOrder		int OUTPUT,
    @TabLayout		int OUTPUT,
    @NbPanes		int OUTPUT,
    @Width0			int OUTPUT,
    @Width1			int OUTPUT,
    @Width2			int OUTPUT,
    @Width3			int OUTPUT,
    @Width4			int OUTPUT,
    @ParentTabID	int OUTPUT,
    @AuthRoles		nvarchar (512) OUTPUT
)
AS
-- First get portalid from alias 
EXEC @PortalId			=	adn_GetPortalFromAlias @PortalAlias
IF @PortalID = -1 RETURN
-- the real tab portal 
SELECT @PortalName		=	PortalName,
		@BaseAlias		=	PortalAlias,
		@PortalPath		=	PortalPath,
		@PortalType     =	PortalType
FROM adn_portals WHERE PortalID = @PortalID 

DECLARE @TstTabID	int

-- then, get Out Params 
IF @TabID = 0 
    SELECT TOP 1
        @TabID			=	adn_Tabs.TabID,
        @TstTabID		=	adn_Tabs.TabID,
        @TabOrder		=	adn_Tabs.TabOrder,
        @TabLayout      =	adn_Tabs.TabLayout,
		@NbPanes		=	adn_Tabs.NbPanes,
		@Width0			=	adn_Tabs.Width0,
		@Width1			=	adn_Tabs.Width1,
		@Width2			=	adn_Tabs.Width2,
		@Width3			=	adn_Tabs.Width3,
		@Width4			=	adn_Tabs.Width4,
        @ParentTabID	=	adn_Tabs.ParentTabID,
        @TabName		=	TabName,
		@PageTitle		=	COALESCE ((SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID  AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), TabName), 
		@PageKeyPhrase	=	COALESCE ((SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID  AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), TabName), 
		@UrlName		=	adn_Tabs.UrlName,
		@TabSkinID		=	adn_Tabs.TabSkinID,
        @AuthRoles		=	adn_Tabs.AuthorizedRoles
    FROM adn_Tabs WHERE (( adn_Tabs.PortalID = -2 ) OR ( adn_Tabs.PortalID = @PortalID )) 
    ORDER BY adn_tabs.PortalID ASC, ParentTabID ASC, TabOrder ASC
ELSE 
    SELECT
        @TstTabID		=	adn_Tabs.TabID,
        @TabName		=	TabName,
		@PageTitle		=	COALESCE ((SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID  AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), TabName), 
		@PageKeyPhrase	=	COALESCE ((SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID  AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), TabName), 
		@UrlName		=	adn_Tabs.UrlName,
        @TabOrder       =	adn_Tabs.TabOrder,
        @TabLayout      =	adn_Tabs.TabLayout,
		@NbPanes		=	adn_Tabs.NbPanes,
		@Width0			=	adn_Tabs.Width0,
		@Width1			=	adn_Tabs.Width1,
		@Width2			=	adn_Tabs.Width2,
		@Width3			=	adn_Tabs.Width3,
		@Width4			=	adn_Tabs.Width4,
        @ParentTabID    =	adn_Tabs.ParentTabID,
		@TabSkinID		=	adn_Tabs.TabSkinID,
        @AuthRoles		=	adn_Tabs.AuthorizedRoles
    FROM adn_Tabs INNER JOIN adn_Portals ON adn_Tabs.PortalID = adn_Portals.PortalID
    WHERE TabID=@TabID 
/* Not found, page is not in good portal */
IF ( @TstTabID IS NULL )
	RETURN
/* Get Crm Server */
SELECT TOP 1 c.* FROM adn_CrmServer c INNER JOIN adn_PortalCrmServer p ON c.CrmServerId = p.CrmServerId WHERE p.PortalId = @PortalID
/* Get Tabs list */
SELECT 
	TabName,
	COALESCE (
		(SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), 
			TabName)  AS PageTitle, 
	COALESCE (
		(SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), 
			TabName)  AS PageKeyPhrase, 
	AuthorizedRoles, 
	TabID, 
	PortalID,
	ParentTabID, 
	TabOrder, 
	TabSkinID,
    TabLayout,
    UrlName,
	( SELECT count(adn_Modules.ModuleID) FROM adn_Modules 
		INNER JOIN adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID 
        WHERE adn_Modules.TabID = adn_tabs.TabID AND ( (adn_ModuleDefinitions.PortalID = -2) OR (adn_ModuleDefinitions.PortalID = @PortalID)) ) AS nbModules
FROM adn_Tabs WHERE ((PortalID = -2) OR (PortalID = @PortalID))
ORDER BY adn_tabs.PortalID ASC, ParentTabID ASC, TabOrder ASC
/* Then, get the list of module info related to current Page */
SELECT * FROM adn_Modules INNER JOIN
  adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID INNER JOIN
  adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
WHERE ( (adn_Modules.TabID = @TabID) OR ((adn_Modules.ShowEveryWhere = 1) AND (adn_ModuleDefinitions.PortalID = @PortalID)) )
	AND adn_GeneralModuleDefinitions.Lock = 0
ORDER BY adn_Modules.ModuleOrder
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortalSettingsLangList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalSettingsLangList]
GO

CREATE PROCEDURE [dbo].[adn_GetPortalSettingsLangList]
(
    @PortalAlias   nvarchar(50)
)
AS
/* First get portalid from alias */
DECLARE @PortalId int
EXEC @PortalId= adn_GetPortalFromAlias @PortalAlias
IF @PortalID = -1 RETURN
SELECT adn_PortalSettings.SettingValue
FROM adn_PortalSettings WHERE (adn_PortalSettings.PortalId = @PortalId) AND (adn_PortalSettings.SettingName = N'SITESETTINGS_LANGLIST')
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPortalsModules]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalsModules]
GO

CREATE PROCEDURE [dbo].[adn_GetPortalsModules]
(
    @ModuleID  uniqueidentifier
)
AS
SELECT adn_Portals.PortalID, adn_Portals.PortalAlias, adn_Portals.PortalName, adn_ModuleDefinitions.ModuleDefID
	FROM adn_Portals LEFT OUTER JOIN adn_ModuleDefinitions ON adn_Portals.PortalID = adn_ModuleDefinitions.PortalID
	WHERE (adn_ModuleDefinitions.GeneralModDefID = @ModuleID)
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetSingleModuleDefinition]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleModuleDefinition]
GO

CREATE PROCEDURE [dbo].[adn_GetSingleModuleDefinition]
(
    @GeneralModDefID uniqueidentifier
)
AS
SELECT
	GeneralModDefID, 
    FriendlyName,
    DesktopSrc,
    Usage,
	VersionType,
	Category,
    [Admin],
    [Lock]
FROM adn_GeneralModuleDefinitions
WHERE (GeneralModDefID = @GeneralModDefID)
GO

-- Tabs/Pages
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeleteTab]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteTab]
GO

CREATE PROCEDURE [dbo].[adn_DeleteTab]
(
    @TabID int
)
AS
DECLARE @PortalId int
SELECT @PortalID=PortalID FROM adn_Tabs WHERE TabID = @TabID
IF ((@PortalID = -2) OR (@PortalID = -3)) RETURN
IF (@PortalID = -1)
	DELETE FROM adn_Tabs WHERE TabID = @TabID
ELSE
UPDATE adn_Tabs 
	SET PortalID	= -1 ,
	ParentTabID	=	NULL
	WHERE TabID = @TabID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_RecoverPage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_RecoverPage]
GO

CREATE PROCEDURE [dbo].[adn_RecoverPage]
(
    @TabID int,
    @NewPortalID int,
    @NewParentPageID int,
    @TabLayout int
)
AS
DECLARE @PortalId int
SELECT @PortalID=PortalID FROM adn_Tabs WHERE TabID = @TabID
IF NOT ((@PortalID = -3) OR (@PortalID = -1)) RETURN
IF (@NewParentPageID = 0 )
	SELECT @NewParentPageID = NULL
UPDATE adn_Tabs 
	SET PortalID	= @NewPortalID, 
	ParentTabID		= @NewParentPageID,
	TabLayout		= @TabLayout
WHERE TabID = @TabID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetUrlName]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetUrlName]
GO

CREATE PROCEDURE [dbo].[adn_GetUrlName]
(
    @TabID           int
)
AS
SELECT  UrlName,TabLayout FROM adn_Tabs WHERE TabID = @TabID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateUrlName]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateUrlName]
GO

CREATE PROCEDURE [dbo].[adn_UpdateUrlName]
(
    @TabID           int,
    @UrlName         nvarchar(50)
)
AS
UPDATE adn_Tabs SET UrlName=@UrlName WHERE TabID = @TabID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateUrlAndLayout]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateUrlAndLayout]
GO

CREATE PROCEDURE [dbo].[adn_UpdateUrlAndLayout]
(
    @TabID           int,
    @UrlName         nvarchar(50),
    @TabLayout		int
)
AS
UPDATE adn_Tabs SET UrlName=@UrlName, TabLayout=@TabLayout WHERE TabID = @TabID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAllUrlNameByPortal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllUrlNameByPortal]
GO

CREATE PROCEDURE [dbo].[adn_GetAllUrlNameByPortal]
(
    @PortalID   int
)
AS
SELECT * FROM adn_Tabs WHERE ( (PortalID = @PortalID) OR (PortalID = -2) ) AND ( UrlName IS NOT NULL) AND NOT ( UrlName = '')
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAllUrlName]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllUrlName]
GO

CREATE PROCEDURE [dbo].[adn_GetAllUrlName]
AS
SELECT * FROM adn_Tabs WHERE ( UrlName IS NOT NULL) AND NOT ( UrlName = '')
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAllLoginPages]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllLoginPages]
GO

CREATE PROCEDURE [dbo].[adn_GetAllLoginPages]
(
    @PortalID   int
)
AS
SELECT  * FROM adn_Tabs WHERE ( (PortalID = @PortalID) OR (PortalID = -2) ) AND  ((TabLayout & 0x20) = 0x20)
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAllPagesByFlag]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllPagesByFlag]
GO

CREATE PROCEDURE [dbo].[adn_GetAllPagesByFlag]
(
    @PortalID   int,
    @TabLayout		int
)
AS
SELECT  * FROM adn_Tabs WHERE ( (PortalID = @PortalID) OR (PortalID = -2) ) AND ((TabLayout & @TabLayout) = @TabLayout)
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateTabOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateTabOrder]
GO

CREATE PROCEDURE [dbo].[adn_UpdateTabOrder]
(
    @TabID           int,
    @TabOrder        int
)
AS
UPDATE adn_Tabs SET TabOrder = @TabOrder WHERE TabID = @TabID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateTabName]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateTabName]
GO

CREATE PROCEDURE [dbo].[adn_UpdateTabName]
(
    @TabID           int,
    @TabName         nvarchar(50)
)
AS
UPDATE adn_Tabs SET TabName = @TabName WHERE TabID = @TabID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetAllTabs]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllTabs]
GO

CREATE PROCEDURE [dbo].[adn_GetAllTabs]
AS
SELECT *,(SELECT count(*) FROM adn_Modules INNER JOIN adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID 
	WHERE adn_Modules.TabID = adn_tabs.TabID ) AS nbModules FROM adn_Tabs
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddTab]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddTab]
GO

CREATE PROCEDURE [dbo].[adn_AddTab]
(
	@PortalID		int,
	@ParentTabID	int,
	@TabName		nvarchar(50),
	@TabSkinID	nvarchar(50),
	@TabOrder		int,     
    @NbPanes		int,
    @Width0			int,
    @Width1			int,
    @Width2			int,
    @Width3			int,
    @Width4			int,
	@AuthorizedRoles	nvarchar (512),
	@TabID		int OUTPUT     
)
AS
IF (@ParentTabID = 0)
BEGIN
	SET @ParentTabID = NULL
END
INSERT INTO adn_Tabs
(
   ParentTabID,  
    TabOrder,
    NbPanes,
    Width0,
    Width1,
    Width2,
    Width3,
    Width4,
    PortalID,
    TabName,
    TabSkinID,
    AuthorizedRoles
)
VALUES
(
	@ParentTabID, 
	@TabOrder,
    @NbPanes,
    @Width0,
    @Width1,
    @Width2,
    @Width3,
    @Width4,
	@PortalID,
	@TabName,
	@TabSkinID,
	@AuthorizedRoles
)
SELECT @TabID = @@IDENTITY
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetTabsParent]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetTabsParent]
GO

CREATE PROCEDURE [dbo].[adn_GetTabsParent]
(
	@PortalID int,
	@TabID int
)
AS
--Create a Temporary table to hold the tabs for this query
CREATE TABLE #TabTree
(
    [TabID] [int],
    [TabName] [nvarchar] (100),
    [ParentTabID] [int],
    [TabOrder] [int],
    [NestLevel] [int],
    [TreeOrder] [varchar] (1000)
)
SET NOCOUNT ON  -- Turn off echo of "... row(s) affected"
DECLARE @LastLevel smallint
SET @LastLevel = 0
-- First, the parent Levels
INSERT INTO     #TabTree
SELECT  TabID,
        TabName,
        ParentTabID,
        TabOrder,
        0,
        cast(100000000 + TabOrder AS varchar)
FROM adn_Tabs
WHERE ParentTabID IS NULL AND PortalID =@PortalID ORDER BY TabOrder
-- Next, the children Levels
WHILE (@@rowcount > 0)
BEGIN
  SET @LastLevel = @LastLevel + 1
  INSERT #TabTree (TabID, TabName, ParentTabID, TabOrder, NestLevel, TreeOrder) 
        SELECT  adn_Tabs.TabID,
                Replicate('-', @LastLevel *2) + adn_Tabs.TabName,
                adn_Tabs.ParentTabID,
                adn_Tabs.TabOrder,
                @LastLevel,
                cast(#TabTree.TreeOrder AS varchar) + '.' + cast(100000000 + adn_Tabs.TabOrder AS varchar)
        FROM    adn_Tabs join #TabTree on adn_Tabs.ParentTabID= #TabTree.TabID
        WHERE   EXISTS (SELECT 'X' FROM #TabTree WHERE TabID = adn_Tabs.ParentTabID AND NestLevel = @LastLevel - 1)
         AND PortalID =@PortalID
        ORDER BY #TabTree.TabOrder
END
--Get the Orphans
INSERT #TabTree (TabID, TabName, ParentTabID, TabOrder, NestLevel, TreeOrder) 
    SELECT  adn_Tabs.TabID,
            '(Orphan)' + adn_Tabs.TabName,
            adn_Tabs.ParentTabID,
            adn_Tabs.TabOrder,
            999999999,
            '999999999'
    FROM    adn_Tabs 
    WHERE   NOT EXISTS (SELECT 'X' FROM #TabTree WHERE TabID = adn_Tabs.TabID)
             AND PortalID =@PortalID
-- Reorder the tabs by using a 2nd Temp table AND an identity field to keep them straight.
SELECT IDENTITY(int,1,2) AS ord , cast(TabID AS varchar) AS TabID into #tabs
FROM #TabTree ORDER BY NestLevel, TreeOrder
-- Change the TabOrder in the sirt temp table so that tabs are ordered in sequence
update #TabTree set TabOrder=(select ord from #tabs WHERE cast(#tabs.TabID AS int)=#TabTree.TabID) 
-- Return Temporary Table
SELECT TabID, TabName, TreeOrder FROM #TabTree 
UNION
SELECT 0 TabID, ' ROOT_LEVEL' TabName, '-1' AS TreeOrder
ORDER BY TreeOrder
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateTab]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateTab]
GO

--Prevents orphaning a tab or placing tabs in an infinte recursive loop
CREATE PROCEDURE [dbo].[adn_UpdateTab]
(
    @PortalID        int,
    @TabID           int,
    @ParentTabID     int,
    @TabOrder        int,
    @NbPanes		int,
    @Width0			int,
    @Width1			int,
    @Width2			int,
    @Width3			int,
    @Width4			int,
    @TabName         nvarchar(50),
    @TabSkinID       nvarchar(50),
    @AuthorizedRoles nvarchar(512)
)
AS
IF (@ParentTabID = 0) 
    SET @ParentTabID = NULL
IF NOT EXISTS ( SELECT * FROM adn_Tabs WHERE  TabID = @TabID )
	INSERT INTO adn_Tabs (
		PortalID,
		ParentTabID,
		TabOrder,
		NbPanes,
		Width0,
		Width1,
		Width2,
		Width3,
		Width4,
		TabName,
		TabSkinID,
		AuthorizedRoles
	) 
	VALUES (
		@PortalID,
		@TabOrder,
		@NbPanes,
		@Width0,
		@Width1,
		@Width2,
		@Width3,
		@Width4,
		@ParentTabID,
		@TabName,
		@TabSkinID,
		@AuthorizedRoles
	)
ELSE
--Check the Tab recursion so Tab is not placed into an infinite loop when building Tab Tree
BEGIN TRAN
--If the Update breaks the tab from having a path back to the root then do not Update
UPDATE adn_Tabs
SET
    ParentTabID = @ParentTabID,
    TabOrder	= @TabOrder,
    NbPanes	=	@NbPanes,
    Width0	=	@Width0,
    Width1	=	@Width1,
    Width2	=	@Width2,
    Width3	=	@Width3,
    Width4	=	@Width4,
    TabName = @TabName,
    TabSkinID = @TabSkinID,
    AuthorizedRoles = @AuthorizedRoles
WHERE TabID = @TabID
--Create a Temporary table to hold the tabs
CREATE TABLE #TabTree
(
	[TabID] [int],
	[TabName] [nvarchar] (100),
	[TabSkinID] [nvarchar] (50),
	[ParentTabID] [int],
	[TabOrder] [int],
	[NestLevel] [int],
	[TreeOrder] [varchar] (1000)
)
SET NOCOUNT ON	-- Turn off echo of "... row(s) affected"
DECLARE @LastLevel smallint
SET @LastLevel = 0
-- First, the parent Levels
INSERT INTO	#TabTree
SELECT 	TabID,TabName,TabSkinID,ParentTabID,TabOrder,0,cast(100000000 + TabOrder AS varchar)
FROM adn_Tabs WHERE ( ParentTabID IS NULL ) AND ( PortalID =@PortalID OR PortalID = -2 ) ORDER BY TabOrder
-- Next, the children Levels
WHILE (@@rowcount > 0)
BEGIN
  SET @LastLevel = @LastLevel + 1
  INSERT #TabTree (TabID, TabName, TabSkinID, ParentTabID, TabOrder, NestLevel, TreeOrder) 
	SELECT 	adn_Tabs.TabID,Replicate('-', @LastLevel *2) + adn_Tabs.TabName,adn_Tabs.TabSkinID,adn_Tabs.ParentTabID,adn_Tabs.TabOrder,@LastLevel,
		cast(#TabTree.TreeOrder AS varchar) + '.' + cast(100000000 + adn_Tabs.TabOrder AS varchar)
	FROM adn_Tabs JOIN #TabTree ON adn_Tabs.ParentTabID = #TabTree.TabID
	WHERE EXISTS (SELECT 'X' FROM #TabTree WHERE TabID = adn_Tabs.ParentTabID AND NestLevel = @LastLevel - 1)
	 AND ( PortalID = @PortalID OR PortalID = -2 ) 
	ORDER BY #TabTree.TabOrder
END
--Check that the Tab is found in the Tree.  If it is not then we abort the Update
IF NOT EXISTS (SELECT TabID from #TabTree WHERE TabID=@TabID)
BEGIN
	ROLLBACK TRAN
	--If we want to modify the TabLayout code then we can throw an error AND catch it.
	RAISERROR('Not allowed to choose that parent.',11,1)
END
ELSE
COMMIT TRAN
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_UpdatePagePanes]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdatePagePanes]
GO

CREATE PROCEDURE [dbo].[adn_UpdatePagePanes]
(
    @TabID           int,
    @NbPanes		int,
    @Width0			int,
    @Width1			int,
    @Width2			int,
    @Width3			int,
    @Width4			int
)
AS
UPDATE adn_Tabs
SET
    NbPanes	=	@NbPanes,
    Width0	=	@Width0,
    Width1	=	@Width1,
    Width2	=	@Width2,
    Width3	=	@Width3,
    Width4	=	@Width4
WHERE TabID = @TabID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetAllPortalTabs]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllPortalTabs]
GO

CREATE PROCEDURE [dbo].[adn_GetAllPortalTabs]
(
    @PortalID int,
	@PortalLanguage nvarchar(12)
)
AS
SELECT
	TabName,
	COALESCE (
	(SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), 
			TabName)  AS PageTitle, 
	COALESCE (
	(SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), 
			TabName)  AS PageKeyPhrase, 
	AuthorizedRoles, 
	TabID, 
	PortalID,
	ParentTabID, 
	TabOrder, 
	TabSkinID,
    TabLayout,
	NbPanes,
	Width0,
	Width1,
	Width2,
	Width3,
	Width4,
   (SELECT count(*) FROM adn_Modules INNER JOIN adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID 
    WHERE adn_Modules.TabID = adn_tabs.TabID AND ( (adn_ModuleDefinitions.PortalID = -2) OR (adn_ModuleDefinitions.PortalID = @PortalID)) ) AS nbModules
 FROM adn_Tabs WHERE ((PortalID = @PortalID) OR (PortalID = -2 )) ORDER BY ParentTabID ASC, TabOrder ASC
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetPageTabOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPageTabOrder]
GO

CREATE PROCEDURE [dbo].[adn_GetPageTabOrder]
(
    @PortalID int,
	@TabID int
)
AS
SELECT TabOrder FROM adn_Tabs WHERE PortalID = @PortalID AND TabID = @TabID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetPortalPage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPortalPage]
GO

CREATE PROCEDURE [dbo].[adn_GetPortalPage]
(
	@TabID int,
	@PortalLanguage nvarchar(12)
)
AS
SELECT 
	TabName,
	COALESCE (
	(SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), 
			TabName)  AS PageTitle, 
	COALESCE (
	(SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), 
			TabName)  AS PageKeyPhrase, 
	AuthorizedRoles, 
	TabID, 
	PortalID,
	ParentTabID, 
	TabOrder, 
	TabSkinID,
    TabLayout,
	NbPanes,
	Width0,
	Width1,
	Width2,
	Width3,
	Width4,
   (SELECT COUNT(*) FROM adn_Modules INNER JOIN adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID 
    WHERE adn_Modules.TabID = adn_tabs.TabID AND adn_ModuleDefinitions.PortalID = adn_Tabs.PortalID ) AS nbModules
 FROM adn_Tabs WHERE TabID = @TabID 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetTabsFlat]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetTabsFlat]
GO

CREATE PROCEDURE [dbo].[adn_GetTabsFlat]
(
	@PortalID int
)
AS
--Create a Temporary table to hold the tabs for this query
CREATE TABLE #TabTree
(
    [TabID] [int],
    [PortalID] [int],
    [TabName] [nvarchar] (100),
    [ParentTabID] [int],
	[TabSkinID]	nvarchar(50),
    [TabOrder] [int],
	[TabLayout] [int] NULL ,
    [NestLevel] [int],
    [TreeOrder] [varchar] (1000),
    [nbModules] [int]
)
SET NOCOUNT ON  -- Turn off echo of "... row(s) affected"
DECLARE @LastLevel smallint
SET @LastLevel = 0
-- First, the parent levels
INSERT INTO #TabTree
SELECT  TabID,
        PortalID,
        TabName,
        ParentTabID,
        TabSkinID,
        TabOrder,
        TabLayout,
        0,
        cast(100000000 + TabOrder as varchar),
   (SELECT count(*) FROM adn_Modules INNER JOIN adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID 
		WHERE adn_Modules.TabID = adn_tabs.TabID AND ((adn_ModuleDefinitions.PortalID = @PortalID) OR (adn_ModuleDefinitions.PortalID = -2)) ) AS nbModules
FROM adn_Tabs WHERE ( ParentTabID IS NULL ) AND (( PortalID =@PortalID ) OR (PortalID = -2))
ORDER BY TabOrder
-- Next, the children levels
WHILE (@@rowcount > 0)
BEGIN
  SET @LastLevel = @LastLevel + 1
  INSERT #TabTree (TabID,PortalID, TabName, ParentTabID,TabSkinID,TabOrder,TabLayout,NestLevel, TreeOrder,nbModules) 
    SELECT adn_Tabs.TabID,
			adn_Tabs.PortalID,
            Replicate('-', @LastLevel *2) + adn_Tabs.TabName,
            adn_Tabs.ParentTabID,
            adn_Tabs.TabSkinID,
            adn_Tabs.TabOrder,
            adn_Tabs.TabLayout,
            @LastLevel,
            cast(#TabTree.TreeOrder as varchar) + '.' + cast(100000000 + adn_Tabs.TabOrder as varchar),
		   (SELECT count(*) FROM adn_Modules INNER JOIN adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID 
				WHERE adn_Modules.TabID = adn_tabs.TabID AND ((adn_ModuleDefinitions.PortalID = @PortalID) OR (adn_ModuleDefinitions.PortalID = -2 )) ) AS nbModules
	FROM adn_Tabs join #TabTree on adn_Tabs.ParentTabID= #TabTree.TabID
    WHERE EXISTS (SELECT 'X' FROM #TabTree WHERE TabID = adn_Tabs.ParentTabID AND NestLevel = @LastLevel - 1)
    AND (( PortalID =@PortalID) OR ( PortalID =-2))
    ORDER BY #TabTree.TabOrder
END
--Get the Orphans
INSERT #TabTree (TabID,PortalID,TabName, ParentTabID, TabSkinID,TabOrder, TabLayout,NestLevel, TreeOrder,nbModules) 
    SELECT  adn_Tabs.TabID,
			adn_Tabs.PortalID,
            '(Orphan)' + adn_Tabs.TabName,
            adn_Tabs.ParentTabID,
            adn_Tabs.TabSkinID,
            adn_Tabs.TabOrder,
            adn_Tabs.TabLayout,
            999999999,
            '999999999',
		   (SELECT count(*) FROM adn_Modules INNER JOIN adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID 
				WHERE adn_Modules.TabID = adn_tabs.TabID AND ((adn_ModuleDefinitions.PortalID = @PortalID) OR (adn_ModuleDefinitions.PortalID = -2 )) ) AS nbModules
    FROM adn_Tabs 
    WHERE NOT EXISTS (SELECT 'X' FROM #TabTree WHERE TabID = adn_Tabs.TabID) AND (( PortalID =@PortalID) OR ( PortalID =-2))
-- Reorder the tabs by using a 2nd Temp table AND an identity field to keep them straight.
SELECT IDENTITY(int,1,2) AS ord , cast(TabID as varchar) AS TabID INTO #tabs FROM #TabTree ORDER BY nestlevel, TreeOrder
-- Change the TabOrder in the sirt temp table so that tabs are ordered in sequence
UPDATE #TabTree SET TabOrder=(SELECT ord FROM #tabs WHERE cast(#tabs.TabID as int)=#TabTree.TabID) 
-- Return Temporary Table
SELECT TabID,PortalID, ParentTabID,TabSkinID, TabName, TabOrder,TabLayout,NestLevel,nbModules FROM #TabTree ORDER BY TreeOrder
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateTabParent]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateTabParent]
GO

CREATE PROCEDURE [dbo].[adn_UpdateTabParent]
(
    @PortalID        int,
    @TabID           int,
    @ParentTabID     int
)
AS
IF (@ParentTabID = 0) SET @ParentTabID = NULL
UPDATE adn_Tabs SET ParentTabID = @ParentTabID WHERE TabID = @TabID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetPageByParentID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPageByParentID]
GO

CREATE  PROCEDURE adn_GetPageByParentID
(
	@PortalID int,
    @ParentTabID     int,
	@TabName [nvarchar] (50)
)
AS
SELECT TabID FROM adn_Tabs WHERE TabName=@TabName AND ParentTabID = @ParentTabID AND PortalID = @PortalID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetPagesParentTabID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPagesParentTabID]
GO

CREATE  PROCEDURE adn_GetPagesParentTabID
(
	@PortalID int,
	@TabID int
)
AS
SELECT ParentTabID FROM adn_Tabs WHERE TabID = @TabID AND PortalID = @PortalID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetPageTree]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPageTree]
GO

CREATE PROCEDURE [dbo].[adn_GetPageTree]
(
	@PortalID int
)
AS
--drop table #tree
-- Get the hierarchy
CREATE TABLE #tree (id int, sequence varchar(1000), levelNo int, TabOrder int)
-- insert top level (to get sub tree just insert relevent id here)
INSERT #tree 
SELECT TabID, (convert(varchar(10),Len(adn_Tabs.TabOrder)) + '.' + convert(varchar(10),adn_Tabs.TabOrder)), 1, TabOrder
FROM adn_Tabs WHERE ((PortalId = @PortalID) OR (PortalId = -2)) AND (ParentTabID is null)
ORDER BY adn_Tabs.TabOrder

DECLARE @i int
SELECT @i = 0
-- keep going until no more rows added
WHILE @@rowcount > 0
BEGIN
     SELECT @i = @i + 1
     INSERT #tree
     -- Get all children of previous level
     SELECT adn_Tabs.TabID, 
	#tree.sequence + '.'+ convert(varchar(10),Len(adn_Tabs.TabOrder)) + '.' + convert(varchar(10),adn_Tabs.TabOrder), 
	@i + 1, 
	adn_Tabs.TabOrder
     FROM adn_Tabs, #tree 
     WHERE #tree.levelNo = @i AND adn_Tabs.ParentTabID = #tree.id
     ORDER BY adn_Tabs.TabOrder
END

-- output with hierarchy formatted
SELECT adn_Tabs.TabID, adn_Tabs.PortalID,
	adn_Tabs.ParentTabID, 
	adn_Tabs.TabOrder, 
	adn_Tabs.TabName, 
	#tree.levelNo , 
	Replicate('-', (#tree.levelNo) * 2) + adn_Tabs.TabName as PageOrder
	--, #tree.sequence
FROM #tree, adn_Tabs WHERE #tree.id = adn_Tabs.TabID ORDER BY #tree.sequence--, adn_Tabs.TabOrder

DROP TABLE #tree
--drop table #z
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetTabCustomSettings]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetTabCustomSettings]
GO

CREATE PROCEDURE [dbo].[adn_GetTabCustomSettings]
(
    @TabID int
)
AS
SELECT
    SettingName,
    SettingValue
FROM adn_TabSettings
WHERE TabID = @TabID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetTabSingleCustomSetting]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetTabSingleCustomSetting]
GO

CREATE PROCEDURE [dbo].[adn_GetTabSingleCustomSetting]
(
    @TabID int,
    @SettingName nvarchar(50),
    @SettingValue nvarchar(1500) OUTPUT
)
AS
SELECT @SettingValue=SettingValue FROM adn_TabSettings WHERE TabID = @TabID AND SettingName=@SettingName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetTabsByPortal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetTabsByPortal]
GO

/* Get Tabs list */
CREATE PROCEDURE [dbo].[adn_GetTabsByPortal]
(
    @PortalID   int
)
AS
SELECT TabName, AuthorizedRoles, TabID, TabOrder, ParentTabID, PortalID,TabSkinID
	FROM adn_Tabs WHERE (PortalID = @PortalID) ORDER BY ParentTabID ASC, TabOrder ASC
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetTabSettings]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetTabSettings]
GO

CREATE PROCEDURE [dbo].[adn_GetTabSettings]
(
    @TabID   int,
    @PortalID   int,
    @PortalLanguage nvarchar(12)
)
AS
IF (@TabID > 0)
/* Get Tabs list */
SELECT     
	TabName,
   COALESCE (
   (SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), 
	TabName)  AS PageTitle, 
   COALESCE (
   (SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), 
	TabName)  AS PageKeyPhrase, 
	AuthorizedRoles, 
	TabID, 
	PortalID, 
	TabOrder, 
	TabSkinID,
	ParentTabID, 
	TabLayout,
	UrlName,
	NbPanes,
	Width0,
	Width1,
	Width2,
	Width3,
	Width4,
 PortalID,
 (SELECT COUNT(*) FROM adn_Modules INNER JOIN adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID 
    WHERE adn_Modules.TabID = adn_tabs.TabID AND adn_ModuleDefinitions.PortalID = adn_Tabs.PortalID ) AS nbModules
FROM adn_Tabs WHERE (ParentTabID = @TabID) AND ((PortalID = @PortalID) OR (PortalID = -2)) ORDER BY ParentTabID ASC, TabOrder ASC
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateTabCustomSettings]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateTabCustomSettings]
GO

CREATE PROCEDURE [dbo].[adn_UpdateTabCustomSettings]
(
    @TabID int,
    @SettingName   nvarchar(50),
    @SettingValue  nvarchar(1500)
)
AS
IF NOT EXISTS ( SELECT * FROM adn_TabSettings WHERE TabID = @TabID AND SettingName = @SettingName )
	INSERT INTO adn_TabSettings ( TabID,SettingName,SettingValue ) VALUES (@TabID,@SettingName,@SettingValue)
ELSE
	UPDATE adn_TabSettings SET SettingValue = @SettingValue WHERE TabID = @TabID AND SettingName = @SettingName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetTabsinTab]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetTabsinTab]
GO

CREATE PROCEDURE [dbo].[adn_GetTabsinTab]
(
	@PortalID int,
	@TabID int
)
AS
SELECT TabID,PortalID,TabName, ParentTabID, TabOrder, TabSkinID, TabLayout,AuthorizedRoles
	FROM adn_Tabs WHERE (ParentTabID = @TabID) AND ((PortalID = @PortalID) OR (PortalID = -2))
	ORDER BY TabOrder
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetRelatedTables]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetRelatedTables]
GO

CREATE PROCEDURE adn_GetRelatedTables
	@Name	nvarchar(128)
AS
SELECT 
	[InnerResults].[ForeignKeyTableSchema],
	[InnerResults].[ForeignKeyTable], 
	[InnerResults].[ForeignKeyColumn], 
	[InnerResults].[KeyColumn],
	[InnerResults].[ForeignKeyTableID],
	[InnerResults].[KeyTableID],
	[InnerResults].[KeyTableSchema],
	[InnerResults].[KeyTable]
FROM
	(
		SELECT     
			[FKeyTable].[TableName] AS ForeignKeyTable, 
			[FKeyTable].[TableSchema] AS ForeignKeyTableSchema,
			[KeyTable].[TableName] AS KeyTable, 
			[KeyTable].[TableSchema] AS KeyTableSchema,
			[FKeyColumns].[name] AS ForeignKeyColumn, 
	        [KeyColumns].[name] AS KeyColumn,
			[FKeyTable].[ID] AS ForeignKeyTableID,
			[KeyTable].[ID] AS KeyTableID
		FROM sysforeignkeys INNER JOIN
		(
			SELECT     
				[sysobjects].[id] AS ID, 
				[sysobjects].[name] AS TableName,
				[INFORMATION_SCHEMA].[TABLES].[TABLE_SCHEMA] AS TableSchema
			FROM    
				[sysobjects] INNER JOIN [INFORMATION_SCHEMA].[TABLES] 
					ON [sysobjects].[name] = [INFORMATION_SCHEMA].[TABLES].[TABLE_NAME] 
			WHERE   
				([INFORMATION_SCHEMA].[TABLES].[TABLE_TYPE] = 'BASE TABLE')
	       ) FKeyTable ON sysforeignkeys.fkeyid = [FKeyTable].[ID] INNER JOIN
	       (
			SELECT     
				[sysobjects].[id] AS ID, 
				[sysobjects].[name] AS TableName,
				[INFORMATION_SCHEMA].[TABLES].[TABLE_SCHEMA] AS TableSchema
			FROM    
				[sysobjects] INNER JOIN [INFORMATION_SCHEMA].[TABLES] 
					ON [sysobjects].[name] = [INFORMATION_SCHEMA].[TABLES].[TABLE_NAME] 
			WHERE   
				([INFORMATION_SCHEMA].[TABLES].[TABLE_TYPE] = 'BASE TABLE')
	       ) KeyTable ON sysforeignkeys.rkeyid = [KeyTable].[ID] INNER JOIN
                  syscolumns FKeyColumns ON [FKeyTable].[ID] = [FKeyColumns].[id] AND sysforeignkeys.fkey = [FKeyColumns].[colid] INNER JOIN
                  syscolumns KeyColumns ON [KeyTable].[ID] = [KeyColumns].[id] AND sysforeignkeys.rkey = [KeyColumns].[colid]
	) InnerResults
WHERE [InnerResults].[KeyTable] = @Name
GO

-- Modules 
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateModule]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateModule]
GO

CREATE PROCEDURE [dbo].[adn_UpdateModule]
(
    @ModuleID               int,
    @TabID				    int,
    @ModuleOrder            int,
    @ModuleSettingsID		int,
    @ModuleTitle            nvarchar(256),
    @PaneName               nvarchar(50),
    @CacheTime              int,
    @EditRoles              nvarchar(512),
    @AddRoles               nvarchar(512),
    @ViewRoles              nvarchar(512),
    @DeleteRoles            nvarchar(512),
    @PropertiesRoles        nvarchar(512),
    @MoveModuleRoles	    nvarchar(512),
    @DeleteModuleRoles	    nvarchar(512),
    @ShowEveryWhere         bit,
    @SupportCollapsable     bit
)
AS
UPDATE adn_Modules
SET TabID						= @TabID,
    ModuleOrder               	= @ModuleOrder,
    ModuleSettingsID			= @ModuleSettingsID,
    ModuleTitle               	= @ModuleTitle,
    PaneName                  	= @PaneName,
    CacheTime                 	= @CacheTime,
    AuthorizedEditRoles       	= @EditRoles,
    AuthorizedAddRoles        	= @AddRoles,
    AuthorizedViewRoles       	= @ViewRoles,
    AuthorizedDeleteRoles     	= @DeleteRoles,
    AuthorizedPropertiesRoles 	= @PropertiesRoles,
    AuthorizedMoveModuleRoles 	= @MoveModuleRoles,
    AuthorizedDeleteModuleRoles = @DeleteModuleRoles,
    SupportCollapsable			= @SupportCollapsable,
    ShowEveryWhere              = @ShowEveryWhere
WHERE ModuleID = @ModuleID
GO

-- 10/12
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateModuleSettingsID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateModuleSettingsID]
GO

CREATE PROCEDURE [dbo].[adn_UpdateModuleSettingsID]
(
    @ModuleID               int,
    @ModuleSettingsID		int
)
AS
UPDATE adn_Modules
SET ModuleSettingsID = @ModuleSettingsID
WHERE ModuleID = @ModuleID
GO



IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAuthAddRoles]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAuthAddRoles]
GO

CREATE PROCEDURE [dbo].[adn_GetAuthAddRoles]
(
    @ModuleID    int,
    @AccessRoles nvarchar (512) OUTPUT,
    @AddRoles   nvarchar (256) OUTPUT
)
AS
SELECT  
    @AccessRoles = adn_Tabs.AuthorizedRoles,
    @AddRoles   = adn_Modules.AuthorizedAddRoles
FROM adn_Modules INNER JOIN adn_Tabs ON adn_Modules.TabID = adn_Tabs.TabID
WHERE adn_Modules.ModuleID = @ModuleID 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAuthDeleteRoles]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAuthDeleteRoles]
GO

CREATE PROCEDURE [dbo].[adn_GetAuthDeleteRoles]
(
    @ModuleID    int,
    @AccessRoles nvarchar (512) OUTPUT,
    @DeleteRoles   nvarchar (256) OUTPUT
)
AS
SELECT  
    @AccessRoles = adn_Tabs.AuthorizedRoles,
    @DeleteRoles   = adn_Modules.AuthorizedDeleteRoles
FROM adn_Modules INNER JOIN adn_Tabs ON adn_Modules.TabID = adn_Tabs.TabID
WHERE adn_Modules.ModuleID = @ModuleID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAuthEditRoles]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAuthEditRoles]
GO

CREATE PROCEDURE [dbo].[adn_GetAuthEditRoles]
(
    @ModuleID    int,
    @AccessRoles nvarchar (512) OUTPUT,
    @EditRoles   nvarchar (512) OUTPUT
)
AS
SELECT  
    @AccessRoles = adn_Tabs.AuthorizedRoles,
    @EditRoles   = adn_Modules.AuthorizedEditRoles
FROM adn_Modules INNER JOIN adn_Tabs ON adn_Modules.TabID = adn_Tabs.TabID
WHERE adn_Modules.ModuleID = @ModuleID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAuthPropertiesRoles]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAuthPropertiesRoles]
GO

CREATE PROCEDURE [dbo].[adn_GetAuthPropertiesRoles]
(
    @ModuleID    int,
    @AccessRoles nvarchar (512) OUTPUT,
    @PropertiesRoles   nvarchar (512) OUTPUT
)
AS
SELECT  
    @AccessRoles = adn_Tabs.AuthorizedRoles,
    @PropertiesRoles   = adn_Modules.AuthorizedPropertiesRoles
FROM adn_Modules INNER JOIN adn_Tabs ON adn_Modules.TabID = adn_Tabs.TabID
WHERE adn_Modules.ModuleID = @ModuleID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAuthViewRoles]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAuthViewRoles]
GO

CREATE PROCEDURE [dbo].[adn_GetAuthViewRoles]
(
    @ModuleID    int,
    @AccessRoles nvarchar (512) OUTPUT,
    @ViewRoles   nvarchar (512) OUTPUT
)
AS
SELECT  
    @AccessRoles = adn_Tabs.AuthorizedRoles,
    @ViewRoles   = adn_Modules.AuthorizedViewRoles
FROM adn_Modules INNER JOIN adn_Tabs ON adn_Modules.TabID = adn_Tabs.TabID
WHERE adn_Modules.ModuleID = @ModuleID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateModuleViewRole]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateModuleViewRole]
GO
CREATE PROCEDURE [dbo].[adn_UpdateModuleViewRole]
(
    @ModuleID               int,
    @ViewRoles              nvarchar(512)
)
AS
UPDATE adn_Modules
SET AuthorizedViewRoles       	= @ViewRoles
WHERE ModuleID = @ModuleID
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateModuleOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateModuleOrder]
GO

CREATE PROCEDURE [dbo].[adn_UpdateModuleOrder]
(
    @ModuleID           int,
    @ModuleOrder        int,
    @PaneName           nvarchar(50)
)
AS
UPDATE adn_Modules SET ModuleOrder = @ModuleOrder,
    PaneName    = @PaneName
WHERE ModuleID = @ModuleID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetModuleSingleSetting]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModuleSingleSetting]
GO

CREATE PROCEDURE [dbo].[adn_GetModuleSingleSetting]
(
    @ModuleID      int,
    @SettingName nvarchar(50),
    @SettingValue nvarchar(1500) OUTPUT
)
AS
SELECT @SettingValue=SettingValue FROM adn_ModuleSettings WHERE ModuleID = @ModuleID AND SettingName=@SettingName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateModuleSetting]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateModuleSetting]
GO

CREATE PROCEDURE [dbo].[adn_UpdateModuleSetting]
(
    @ModuleID      int,
    @SettingName   nvarchar(50),
    @SettingValue  nvarchar(1500),
    @SettingGroup  int
)
AS
IF NOT EXISTS ( SELECT * FROM adn_ModuleSettings WHERE ModuleID = @ModuleID AND SettingName = @SettingName )
	INSERT INTO adn_ModuleSettings (ModuleID,SettingName,SettingValue,SettingGroup) 
		VALUES (@ModuleID,@SettingName,@SettingValue,@SettingGroup)
ELSE
	UPDATE adn_ModuleSettings SET SettingValue = @SettingValue,
		SettingGroup = @SettingGroup
	WHERE ModuleID = @ModuleID AND SettingName = @SettingName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateUserDeskTop]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateUserDeskTop]
GO

CREATE PROCEDURE [dbo].[adn_UpdateUserDeskTop]
(
    @PortalID 		int,
    @UserID 		UNIQUEIDENTIFIER,
    @ModuleID        	int,
    @TabID          	int,
    @WindowState 	smallint
)
AS
IF ( SELECT count(*) FROM adn_UserDesktop(NOLOCK) WHERE UserID = @UserID AND  TabID = @TabID AND PortalID = @PortalID AND   ModuleID=@ModuleID ) = 0
BEGIN
    -- Transacted insert for download count
    BEGIN TRAN
	INSERT INTO adn_UserDesktop (
	    UserID,
	    ModuleID,
	    TabID,
	    PortalID,
	    State
	) 
	VALUES (
	    @UserID,
	    @ModuleID,
	    @TabID,
	    @PortalID,
	    @WindowState
	)
    COMMIT TRAN
END
ELSE
BEGIN
    -- Transacted insert for download count
    BEGIN TRAN
	UPDATE adn_UserDesktop
	SET UserID=  @UserID,
	    ModuleID=@ModuleID,
	    TabID=@TabID,
	    PortalID=@PortalID,
	    State=@WindowState
	WHERE UserID = @UserID AND  TabID = @TabID AND PortalID = @PortalID AND   ModuleID=@ModuleID
    COMMIT TRAN
END
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeleteUserDeskTop]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteUserDeskTop]
GO

/* deletes all  user desktop values for the specified user */
CREATE PROCEDURE [dbo].[adn_DeleteUserDeskTop]
(
    @UserID      UNIQUEIDENTIFIER,
    @PortalID    int
)
AS
DELETE FROM adn_UserDesktop WHERE UserID = @UserID AND PortalID = @PortalID
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_ModulesUpgradeOldToNew]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_ModulesUpgradeOldToNew]
GO

CREATE PROCEDURE [dbo].[adn_ModulesUpgradeOldToNew]
(
	@OldModuleGuid uniqueidentifier,
	@NewModuleGuid uniqueidentifier
)
/* 
This PROCEDURE replaces all instances of the old module with the new one
Old module entires will be removed.
Module data are not affected.
*/ 
AS
--Get current ids
DECLARE @NewModuleDefID int
SET @NewModuleDefID = (SELECT TOP 1 ModuleDefID FROM ModuleDefinitions WHERE GeneralModDefID = @NewModuleGuid)
DECLARE @OldModuleDefID int
SET @OldModuleDefID = (SELECT TOP 1 ModuleDefID FROM ModuleDefinitions WHERE GeneralModDefID = @OldModuleGuid)

--Update modules
UPDATE Modules
SET ModuleDefID = @NewModuleDefID WHERE ModuleDefID = @OldModuleDefID

-- Drop old definition
DELETE ModuleDefinitions
WHERE ModuleDefID = @OldModuleDefID

DELETE GeneralModuleDefinitions
WHERE GeneralModDefID = @OldModuleGuid
GO


/* Checks to see if adn_GetAuthDeleteModuleRoles already exists AND delete */
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAuthDeleteModuleRoles]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAuthDeleteModuleRoles]
GO
-- 6/5/10
CREATE PROCEDURE [dbo].[adn_GetAuthDeleteModuleRoles]
(
    @ModuleID    int,
    @AccessRoles nvarchar (512) OUTPUT,
    @DeleteModuleRoles   nvarchar (256) OUTPUT
)
AS
SELECT  
    @AccessRoles = adn_Tabs.AuthorizedRoles,
    @DeleteModuleRoles  = adn_Modules.AuthorizedDeleteModuleRoles
FROM adn_Modules INNER JOIN adn_Tabs ON adn_Modules.TabID = adn_Tabs.TabID
WHERE adn_Modules.ModuleID = @ModuleID 
GO

/* Checks to see if adn_GetAuthMoveModuleRoles already exists AND delete */
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAuthMoveModuleRoles]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAuthMoveModuleRoles]
GO
-- 6/5/10
CREATE PROCEDURE [dbo].[adn_GetAuthMoveModuleRoles]
(
    @ModuleID    int,
    @AccessRoles nvarchar (512) OUTPUT,
    @MoveModuleRoles   nvarchar (256) OUTPUT
)
AS
SELECT  
    @AccessRoles = adn_Tabs.AuthorizedRoles,
    @MoveModuleRoles  = adn_Modules.AuthorizedMoveModuleRoles
FROM adn_Modules INNER JOIN adn_Tabs ON adn_Modules.TabID = adn_Tabs.TabID
WHERE adn_Modules.ModuleID = @ModuleID
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetModulesInTab]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModulesInTab]
GO

CREATE PROCEDURE [dbo].[adn_GetModulesInTab]
(
 @PortalID int,
 @TabID int
)
AS
SELECT adn_Modules.ModuleID, adn_ModuleDefinitions.GeneralModDefID
FROM adn_Modules INNER JOIN
     adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID INNER JOIN
     adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
WHERE (adn_Modules.TabID = @TabID) AND (adn_ModuleDefinitions.PortalID = @PortalID)
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetModulesWithDefIDInTab]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetModulesWithDefIDInTab]
GO

CREATE PROCEDURE [dbo].[adn_GetModulesWithDefIDInTab]
(
 @PortalID int,
 @TabID int,
 @GeneralModDefID uniqueidentifier
)
AS
SELECT adn_Modules.*
FROM adn_Modules INNER JOIN
     adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID INNER JOIN
     adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
WHERE (adn_Modules.TabID = @TabID) AND (adn_ModuleDefinitions.PortalID = @PortalID) AND ( @GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID )
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_FindModulesByGuid]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_FindModulesByGuid]
GO

CREATE PROCEDURE [dbo].[adn_FindModulesByGuid]
(
	@PortalID int,
	@Guid uniqueidentifier
)
AS
SELECT adn_Modules.*,adn_Tabs.TabName + '/' + adn_Modules.ModuleTitle + ' (' + adn_GeneralModuleDefinitions.FriendlyName + ')' AS ModTitle
FROM adn_Modules INNER JOIN adn_Tabs ON adn_Modules.TabID = adn_Tabs.TabID INNER JOIN
  adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID INNER JOIN
  adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
WHERE (adn_Tabs.PortalID = @PortalID) AND (adn_ModuleDefinitions.GeneralModDefID = @Guid)
	AND (adn_GeneralModuleDefinitions.Admin = 0) AND (adn_GeneralModuleDefinitions.Lock = 0) 
	AND (adn_GeneralModuleDefinitions.GeneralModDefID <> '23259716-3955-4f19-AB3F-503F99F63171' 
	AND adn_GeneralModuleDefinitions.GeneralModDefID <> 'B47BC165-91A2-4970-ADC5-5A3B727469E3')
ORDER BY TabOrder, adn_Modules.ModuleTitle
GO

-- SiteMap
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetSiteMap]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSiteMap]
GO

CREATE PROCEDURE [dbo].[adn_GetSiteMap]
(
    @PortalAlias	nvarchar(128),
    @TabID         int OUTPUT, 
    @PortalLanguage nvarchar(12),
    @PortalID		int OUTPUT,
    @PortalName		nvarchar(128) OUTPUT,
    @BaseAlias		nvarchar(128) OUTPUT,
    @PortalPath		nvarchar(128) OUTPUT,
    @PortalType      int OUTPUT,
    @TabName		nvarchar (50)  OUTPUT,
    @PageTitle		nvarchar (200)  OUTPUT,
    @PageKeyPhrase	nvarchar (50)  OUTPUT,
    @UrlName		nvarchar (50)  OUTPUT,
    @TabSkinID		nvarchar (50)  OUTPUT,
    @TabOrder		int OUTPUT,
    @TabLayout		int OUTPUT,
    @NbPanes		int OUTPUT,
    @Width0			int OUTPUT,
    @Width1			int OUTPUT,
    @Width2			int OUTPUT,
    @Width3			int OUTPUT,
    @Width4			int OUTPUT,
    @ParentTabID   int OUTPUT,
    @AuthRoles		nvarchar (512) OUTPUT
)
AS
/* First, get portal */
EXEC @PortalId			=	adn_GetPortalFromAlias @PortalAlias
IF @PortalID = -1 RETURN
/* portal info */
SELECT	@PortalName		=	adn_Portals.PortalName,
		@BaseAlias		=	adn_Portals.PortalAlias,
        @PortalPath		=	adn_Portals.PortalPath,
		@PortalType     =	adn_Portals.PortalType
FROM  adn_Portals  WHERE adn_Portals.PortalID = @PortalID

/* then, get Out Params */
IF @TabID = 0 
    SELECT TOP 1
        @TabID			=	adn_SiteMap.PageID,
        @TabOrder		=	adn_SiteMap.PageOrder,
        @TabLayout      =	adn_Tabs.TabLayout,
		@NbPanes		=	adn_Tabs.NbPanes,
		@Width0			=	adn_Tabs.Width0,
		@Width1			=	adn_Tabs.Width1,
		@Width2			=	adn_Tabs.Width2,
		@Width3			=	adn_Tabs.Width3,
		@Width4			=	adn_Tabs.Width4,
        @ParentTabID	=	adn_SiteMap.ParentPageID,
        @TabName		=	TabName,
		@PageTitle		=	COALESCE ((SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID  AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), TabName), 
		@PageKeyPhrase	=	COALESCE ((SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID  AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), TabName), 
		@UrlName		=	adn_Tabs.UrlName,
		@TabSkinID		=	adn_Tabs.TabSkinID,
        @AuthRoles		=	adn_Tabs.AuthorizedRoles
    FROM adn_SiteMap INNER JOIN adn_Tabs ON adn_SiteMap.PageID = adn_Tabs.TabID
    WHERE adn_Tabs.PortalID = @PortalID ORDER BY ParentPageID ASC, TabOrder ASC
ELSE 
BEGIN 
DECLARE @TabPortaID int
SELECT @TabPortaID=PortalID FROM adn_Tabs Where TabID=@TabID
IF ( @TabPortaID < -1)
    SELECT 
        @TabName		=	TabName,
		@PageTitle		=	COALESCE ((SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID  AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), TabName), 
		@PageKeyPhrase	=	COALESCE ((SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID  AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), TabName), 
		@UrlName		=	adn_Tabs.UrlName,
        @TabOrder		=	adn_Tabs.TabOrder,
        @TabLayout		=	adn_Tabs.TabLayout,
		@NbPanes		=	adn_Tabs.NbPanes,
		@Width0			=	adn_Tabs.Width0,
		@Width1			=	adn_Tabs.Width1,
		@Width2			=	adn_Tabs.Width2,
		@Width3			=	adn_Tabs.Width3,
		@Width4			=	adn_Tabs.Width4,
        @ParentTabID	=	adn_Tabs.ParentTabID,
		@TabSkinID		=	adn_Tabs.TabSkinID,
        @AuthRoles		=	adn_Tabs.AuthorizedRoles
    FROM adn_Tabs WHERE TabID = @TabID 
ELSE IF (@TabPortaID = @PortalId )
    SELECT 
        @TabName		=	TabName,
		@PageTitle		=	COALESCE ((SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID  AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), TabName), 
		@PageKeyPhrase	=	COALESCE ((SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID  AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), TabName), 
		@UrlName		=	adn_Tabs.UrlName,
        @TabOrder		=	adn_SiteMap.PageOrder,
        @TabLayout		=	adn_Tabs.TabLayout,
		@NbPanes		=	adn_Tabs.NbPanes,
		@Width0			=	adn_Tabs.Width0,
		@Width1			=	adn_Tabs.Width1,
		@Width2			=	adn_Tabs.Width2,
		@Width3			=	adn_Tabs.Width3,
		@Width4			=	adn_Tabs.Width4,
        @ParentTabID	=	adn_SiteMap.ParentPageID,
		@TabSkinID		=	adn_Tabs.TabSkinID,
        @AuthRoles		=	adn_Tabs.AuthorizedRoles
    FROM adn_SiteMap INNER JOIN adn_Tabs ON adn_SiteMap.PageID = adn_Tabs.TabID
    WHERE PageID = @TabID 
ELSE RETURN
END
/* Get Crm Server */
SELECT TOP 1 c.* FROM adn_CrmServer c INNER JOIN adn_PortalCrmServer p ON c.CrmServerId = p.CrmServerId WHERE p.PortalId = @PortalID
/* Get Tabs list */
SELECT 	
	TabName,
	COALESCE (
	   (SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_SiteMap.PageID  AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), 
		TabName)  AS PageTitle, 
	COALESCE (
	   (SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_SiteMap.PageID  AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), 
		TabName)  AS PageKeyPhrase, 
	AuthorizedRoles, 
	PageID as TabId, 
	adn_Tabs.PortalID, 
	ParentPageID as ParentTabId, 
	PageOrder as TabOrder, 
	TabSkinID,
    TabLayout,
	UrlName,
	(SELECT COUNT(*) FROM adn_Modules INNER JOIN adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID 
              WHERE adn_Modules.TabID = adn_SiteMap.PageID AND adn_ModuleDefinitions.PortalID = @PortalID ) AS nbModules
	FROM adn_SiteMap INNER JOIN adn_Tabs ON adn_SiteMap.PageID = adn_Tabs.TabID
	WHERE     (adn_SiteMap.PortalID = @PortalID)
	ORDER BY ParentPageID ASC, PageOrder ASC
/* Then, get the DataTable of module info */
SELECT * FROM adn_Modules INNER JOIN
      adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID INNER JOIN
      adn_GeneralModuleDefinitions ON adn_ModuleDefinitions.GeneralModDefID = adn_GeneralModuleDefinitions.GeneralModDefID
	WHERE (adn_Modules.TabID = @TabID) OR (adn_Modules.ShowEveryWhere = 1) AND (adn_ModuleDefinitions.PortalID = @PortalID)
	ORDER BY adn_Modules.ModuleOrder
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteSiteMap]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteSiteMap]
GO

CREATE PROCEDURE [dbo].[adn_DeleteSiteMap]
(
    @PortalID           int
)
AS
DELETE FROM adn_SiteMap WHERE PortalID = @PortalID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetPageSettings]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPageSettings]
GO

CREATE PROCEDURE [dbo].[adn_GetPageSettings]
(
    @TabID   int,
    @PortalID   int,
    @PortalLanguage nvarchar(12)
)
AS
IF (@TabID > 0)
/* Get Tabs list */
SELECT     
	TabName,
	COALESCE (
	(SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_SiteMap.PageID  AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), 
			TabName)  AS PageTitle, 
	COALESCE (
	(SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_SiteMap.PageID  AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), 
			TabName)  AS PageKeyPhrase, 
	AuthorizedRoles, 
	PageID as TabID, 
	adn_Tabs.PortalID, 
	PageOrder as TabOrder, 
	TabSkinID,
	ParentPageID as ParentTabID, 
	TabLayout,
	UrlName,
	NbPanes,
	Width0,
	Width1,
	Width2,
	Width3,
	Width4,
	adn_SiteMap.PortalID,
	(SELECT COUNT(*) FROM adn_Modules INNER JOIN adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID 
    WHERE adn_Modules.TabID = adn_tabs.TabID AND adn_ModuleDefinitions.PortalID = adn_Tabs.PortalID ) AS nbModules
FROM adn_SiteMap INNER JOIN adn_Tabs ON adn_SiteMap.PageID = adn_Tabs.TabID
WHERE (ParentPageID = @TabID)
ORDER BY ParentPageID ASC, PageOrder ASC
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_UpdatePageParent]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdatePageParent]
GO

CREATE PROCEDURE [dbo].[adn_UpdatePageParent]
(
    @PageID           int,
    @ParentPageID     int
)
AS
IF (@ParentPageID = 0) SET @ParentPageID = NULL
UPDATE adn_SiteMap SET ParentPageID = @ParentPageID WHERE PageID = @PageID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetPagesParentPageID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPagesParentPageID]
GO

CREATE  PROCEDURE [dbo].[adn_GetPagesParentPageID]
(
	@PageID int
)
AS
SELECT ParentPageID FROM adn_SiteMap WHERE PageID = @PageID 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetAllPortalPages]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllPortalPages]
GO

CREATE PROCEDURE [dbo].[adn_GetAllPortalPages]
(
	@PortalID int,
	@PortalLanguage nvarchar(12)
)
AS
SELECT 
	TabName,
	COALESCE (
	(SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID AND SettingName = @PortalLanguage AND Len(SettingValue) > 0), 
			TabName)  AS PageTitle, 
	COALESCE (
	(SELECT SettingValue FROM adn_TabSettings  WHERE  TabID = adn_Tabs.TabID AND SettingName = 'PAGEKEYPHRASE_'+@PortalLanguage AND Len(SettingValue) > 0), 
			TabName)  AS PageKeyPhrase, 
	AuthorizedRoles, 
	PageID, 
	PageID as TabID, 
	adn_Tabs.PortalID, 
	ParentPageID, 
	ParentPageID as 	ParentTabID, 
	PageOrder, 
	TabSkinID,
	TabLayout,
	NbPanes,
	Width0,
	Width1,
	Width2,
	Width3,
	Width4,
   (SELECT COUNT(*) FROM adn_Modules INNER JOIN adn_ModuleDefinitions ON adn_Modules.ModuleDefID = adn_ModuleDefinitions.ModuleDefID 
    WHERE adn_Modules.TabID = adn_tabs.TabID AND ( (adn_ModuleDefinitions.PortalID = -2) OR (adn_ModuleDefinitions.PortalID = @PortalID)) ) AS nbModules
 FROM adn_SiteMap INNER JOIN adn_Tabs ON adn_SiteMap.PageID = adn_Tabs.TabID
 WHERE adn_SiteMap.PortalID = @PortalID ORDER BY ParentPageID ASC, PageOrder ASC
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetPagePageOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPagePageOrder]
GO

CREATE PROCEDURE [dbo].[adn_GetPagePageOrder]
(
		@PageID int
)
AS
select PageOrder from adn_SiteMap WHERE PageID = @PageID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdatePageOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdatePageOrder]
GO

CREATE PROCEDURE [dbo].[adn_UpdatePageOrder]
(
    @PageID           int,
    @PageOrder        int
)
AS
UPDATE adn_SiteMap SET PageOrder = @PageOrder WHERE PageID = @PageID
GO


IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddSiteMapPage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddSiteMapPage]
GO

CREATE PROCEDURE [dbo].[adn_AddSiteMapPage]
(
   @PortalID		int,
   @ParentPageID	int,
   @PageOrder		int,     
   @PageID			int 
)
AS
  IF (@ParentPageID = 0)
  BEGIN  
    SET @ParentPageID = NULL
  END
INSERT INTO adn_SiteMap(PortalID,ParentPageID,PageOrder,PageID)
	VALUES (@PortalID,@ParentPageID,@PageOrder,@PageID)
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetPageParent]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetPageParent]
GO

CREATE PROCEDURE [dbo].[adn_GetPageParent]
(
	@PortalID int,
	@PageID int
)
AS
--Create a Temporary table to hold the pages for this query
CREATE TABLE #PageTree
(
        [PageID] [int],
        [TabName] [nvarchar] (100),
        [ParentPageID] [int],
        [PageOrder] [int],
        [NestLevel] [int],
        [TreeOrder] [varchar] (1000)
)
SET NOCOUNT ON  -- Turn off echo of "... row(s) affected"
DECLARE @LastLevel smallint
SET @LastLevel = 0
-- First, the parent Levels
INSERT INTO     #TabTree
SELECT  PageID,
        TabName,
        ParentPageID,
        PageOrder,
        0,
        cast(100000000 + PageOrder AS varchar)
FROM    adn_SiteMap INNER JOIN adn_Tabs ON adn_sitemap.PageID = adn_tabs.TabID
WHERE   ParentPageID IS NULL AND adn_SiteMap.PortalID =@PortalID
ORDER BY PageOrder
-- Next, the children Levels
WHILE (@@rowcount > 0)
BEGIN
  SET @LastLevel = @LastLevel + 1
  INSERT #TabTree (PageID, TabName, ParentPageID, PageOrder, NestLevel, TreeOrder) 
                SELECT  adn_SiteMap.PageID,
                        Replicate('-', @LastLevel *2) + adn_Tabs.TabName,
                        adn_SiteMap.ParentPageID,
                        adn_SiteMap.PageOrder,
                        @LastLevel,
                        cast(#TabTree.TreeOrder AS varchar) + '.' + cast(100000000 + adn_SiteMap.PageOrder AS varchar)
                FROM    adn_SiteMap INNER JOIN adn_Tabs ON adn_sitemap.PageID = adn_tabs.TabID JOIN #TabTree ON adn_Tabs.ParentTabID= #TabTree.PageID
                WHERE   EXISTS (SELECT 'X' FROM #TabTree WHERE TabID = adn_Tabs.ParentPageID AND NestLevel = @LastLevel - 1)
                 AND PortalID =@PortalID
                ORDER BY #TabTree.PageOrder
END
--Get the Orphans
  INSERT #TabTree (PageID, TabName, ParentPageID, PageOrder, NestLevel, TreeOrder) 
                SELECT  adn_SiteMap.PageID,
                        '(Orphan)' + adn_Tabs.TabName,
                        adn_SiteMap.ParentPageID,
                        adn_SiteMap.PageOrder,
                        999999999,
                        '999999999'
                FROM adn_SiteMap INNER JOIN adn_Tabs ON adn_sitemap.PageID = adn_tabs.TabID 
                WHERE   NOT EXISTS (SELECT 'X' FROM #TabTree WHERE PageID = adn_SiteMap.PageID)
                         AND PortalID =@PortalID
-- Reorder the tabs by using a 2nd Temp table AND an identity field to keep them straight.
SELECT IDENTITY(int,1,2) AS ord , cast(PageID AS varchar) AS PageID into #tabs FROM #TabTree ORDER BY NestLevel, TreeOrder
-- Change the TabOrder in the sirt temp table so that tabs are ordered in sequence
UPDATE #TabTree SET PageOrder=(SELECT ord FROM #tabs WHERE CAST(#tabs.PageID AS int)=#TabTree.PageID) 
-- Return Temporary Table
SELECT PageID, TabName, TreeOrder FROM #TabTree 
UNION
SELECT 0 PageID, ' ROOT_LEVEL' TabName, '-1' AS TreeOrder
ORDER BY TreeOrder
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_UpdatePage]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdatePage]
GO

--Prevents orphaning a tab or placing tabs in an infinte recursive loop
CREATE PROCEDURE [dbo].[adn_UpdatePage]
(
    @PageID           int,
    @ParentPageID     int,
    @PageOrder        int,
    @PortalID		int
)
AS
IF (@ParentPageID = 0) 
    SET @ParentPageID = NULL
IF NOT EXISTS (SELECT * FROM adn_SiteMap WHERE PageID = @PageID)
	INSERT INTO adn_SiteMap (ParentPageID,PageOrder,PageID) 
		VALUES (@ParentPageID,@PageOrder,@PageID)
ELSE
--Check the Tab recursion so Tab is not placed into an infinate loop when building Tab Tree
BEGIN TRAN
--If the Update breaks the tab from having a path back to the root then do not Update
UPDATE adn_SiteMap
SET ParentPageID = @ParentPageID,
    PageOrder = @PageOrder
WHERE PageID = @PageID
--Create a Temporary table to hold the tabs
CREATE TABLE #TabTree
(
	[PageID] [int],
	[ParentPageID] [int],
	[PageOrder] [int],
	[NestLevel] [int],
	[TreeOrder] [varchar] (1000)
)
SET NOCOUNT ON	-- Turn off echo of "... row(s) affected"
DECLARE @LastLevel smallint
SET @LastLevel = 0
-- First, the parent Levels
INSERT INTO	#TabTree SELECT PageID,
	ParentPageID,
	PageOrder,
	0,
	cast(100000000 + PageOrder AS varchar)
FROM adn_SiteMap INNER JOIN adn_Tabs ON adn_sitemap.PageID = adn_tabs.TabID 
WHERE	ParentPageID IS NULL AND adn_tabs.PortalID =@PortalID
ORDER BY PageOrder
-- Next, the children Levels
WHILE (@@rowcount > 0)
BEGIN
  SET @LastLevel = @LastLevel + 1
  INSERT #TabTree (PageID, ParentPageID, PageOrder, NestLevel, TreeOrder) 
		SELECT 	adn_SiteMap.PageID,
			adn_Tabs.ParentpageID,
			adn_Tabs.PageOrder,
			@LastLevel,
			cast(#TabTree.TreeOrder AS varchar) + '.' + cast(100000000 + adn_SiteMap.PageOrder AS varchar)
		FROM	adn_SiteMap join #TabTree on adn_SiteMap.ParentPageID= #TabTree.PageID inner join adn_Tabs on adn_sitemap.PageID = adn_tabs.TabID 
		WHERE	EXISTS (SELECT 'X' FROM #TabTree WHERE PageID = adn_SiteMap.ParentPageID AND NestLevel = @LastLevel - 1)
		 AND adn_tabs.PortalID =@PortalID
		ORDER BY #TabTree.PageOrder
END
--Check that the Tab is found in the Tree.  If it is not then we abort the Update
IF NOT EXISTS (SELECT PageID from #TabTree WHERE PageID=@PageID)
BEGIN
	ROLLBACK TRAN
	--If we want to modify the TabLayout code then we can throw an error AND catch it.
	RAISERROR('Not allowed to choose that parent.',11,1)
END
ELSE
COMMIT TRAN
GO


-- Documents
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_Documents]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_Documents] (
	[ItemID] [int] IDENTITY (1,1) NOT NULL ,
	[ModuleID] [int] NOT NULL ,
	[CreatedByUser] [nvarchar] (100) NULL ,
	[CreatedDate] [datetime] NULL ,
	[FileNameUrl] [nvarchar] (250) NULL ,
	[FileFriendlyName] [nvarchar] (150) NULL ,
	[Category] [nvarchar] (50) NULL ,
	[Content] [image] NULL ,
	[ContentType] [nvarchar] (50) NULL ,
	[ContentSize] [int] NULL ,
	CONSTRAINT [PK_adn_Documents] PRIMARY KEY NONCLUSTERED 
	(
		[ItemID]
	),
	CONSTRAINT [FK_adn_Documents_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
)
END
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeleteDocument]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteDocument]
GO

CREATE PROCEDURE [dbo].[adn_DeleteDocument]
(
    @ItemID int
)
AS
DELETE FROM adn_Documents WHERE ItemID = @ItemID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetDocumentContent]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetDocumentContent]
GO

CREATE PROCEDURE [dbo].[adn_GetDocumentContent]
(
    @ItemID int
)
AS
SELECT Content,
    ContentType,
    ContentSize,
    FileFriendlyName,
    FileNameUrl
FROM adn_Documents WHERE ItemID = @ItemID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetDocuments]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetDocuments]
GO

CREATE PROCEDURE [dbo].[adn_GetDocuments]
(
    @ModuleID int
)
AS
SELECT ItemID,
    FileFriendlyName,
    FileNameUrl,
    CreatedByUser,
    CreatedDate,
    Category,
    ContentSize,
    ContentType
FROM adn_Documents WHERE ModuleID = @ModuleID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetSingleDocument]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleDocument]
GO

CREATE PROCEDURE [dbo].[adn_GetSingleDocument]
(
    @ItemID int
)
AS
SELECT  FileFriendlyName,
	    FileNameUrl,
	    CreatedByUser,
	    CreatedDate,
	    Category,
	    ContentSize,
	    ContentType
FROM adn_Documents WHERE ItemID = @ItemID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateDocument]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateDocument]
GO

CREATE PROCEDURE [dbo].[adn_UpdateDocument]
(
    @ItemID           int,
    @ModuleID         int,
    @FileFriendlyName nvarchar(150),
    @FileNameUrl      nvarchar(250),
    @UserName         nvarchar(100),
    @Category         nvarchar(50),
    @Content          image,
    @ContentType      nvarchar(50),
    @ContentSize      int
)
AS
IF (@ItemID=0) OR NOT EXISTS ( SELECT * FROM adn_Documents WHERE ItemID = @ItemID )
INSERT INTO adn_Documents
(   ModuleID,
    FileFriendlyName,
    FileNameUrl,
    CreatedByUser,
    CreatedDate,
    Category,
    Content,
    ContentType,
    ContentSize
)
VALUES
(   @ModuleID,
    @FileFriendlyName,
    @FileNameUrl,
    @UserName,
    GETUTCDATE(),
    @Category,
    @Content,
    @ContentType,
    @ContentSize
)
ELSE
BEGIN
IF (@ContentSize=0)
UPDATE adn_Documents
SET CreatedByUser    = @UserName,
    CreatedDate      = GETUTCDATE(),
    Category         = @Category,
    FileFriendlyName = @FileFriendlyName,
    FileNameUrl      = @FileNameUrl,
    ContentType	     = @ContentType
WHERE ItemID = @ItemID
ELSE
UPDATE adn_Documents
SET CreatedByUser     = @UserName,
    CreatedDate       = GETUTCDATE(),
    Category          = @Category,
    FileFriendlyName  = @FileFriendlyName,
    FileNameUrl       = @FileNameUrl,
    Content           = @Content,
    ContentType       = @ContentType,
    ContentSize       = @ContentSize
WHERE ItemID = @ItemID
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteDocumentGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteDocumentGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateDocumentGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateDocumentGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetDocumentContentGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetDocumentContentGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleDocumentGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleDocumentGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetDocumentsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetDocumentsGlobalized]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DocumentsGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_DocumentsGlobalized](
	[LCID] [int] NOT NULL,
	[ItemID] [int] NOT NULL,
	[ModuleID] [int] NOT NULL,
	[CreatedByUser] [nvarchar](100) NULL,
	[CreatedDate] [datetime] NULL,
	[FileNameUrl] [nvarchar](250) NULL,
	[FileFriendlyName] [nvarchar](150) NULL,
	[Category] [nvarchar](50) NULL,
	[Content] [image] NULL,
	[ContentType] [nvarchar](50) NULL,
	[ContentSize] [int] NULL,
CONSTRAINT [PK_adn_DocumentsGlobalized] PRIMARY KEY NONCLUSTERED 
(
	[LCID] ASC,
	[ItemID] ASC
) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
CONSTRAINT [FK_adn_DocumentsGlobalized_adn_Documents] FOREIGN KEY
([ItemID])
REFERENCES [dbo].[adn_Documents] 
([ItemID]) 
ON DELETE CASCADE NOT FOR REPLICATION ,
CONSTRAINT [FK_adn_DocumentsGlobalized_adn_Modules] FOREIGN KEY
([ModuleID])
REFERENCES [dbo].[adn_Modules] 
([ModuleID]) 
ON DELETE NO ACTION NOT FOR REPLICATION 
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO

CREATE PROCEDURE [dbo].[adn_GetDocumentsGlobalized]
(
    @LCID		int,
    @DefLCID	int,
    @ModuleID	int
)
AS
BEGIN
IF EXISTS (SELECT 1 FROM adn_DocumentsGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
SELECT ItemID,
    FileFriendlyName,
    FileNameUrl,
    CreatedByUser,
    CreatedDate,
    Category,
    ContentSize,
	ContentType
FROM adn_DocumentsGlobalized
WHERE ModuleID = @ModuleID AND LCID = @LCID 
UNION
SELECT ItemID,
    FileFriendlyName,
    FileNameUrl,
    CreatedByUser,
    CreatedDate,
    Category,
    ContentSize,
    ContentType
FROM adn_Documents
WHERE ModuleID = @ModuleID 
AND NOT ItemID IN (SELECT ItemID FROM adn_DocumentsGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID) 
ELSE 
EXEC adn_GetDocuments @ModuleID
END
GO

CREATE PROCEDURE [dbo].[adn_GetSingleDocumentGlobalized]
(
    @LCID		int,
    @DefLCID	int,
    @ItemID int
)
AS
BEGIN
IF EXISTS (SELECT 1 FROM adn_DocumentsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
	SELECT
	    FileFriendlyName,
	    FileNameUrl,
	    CreatedByUser,
	    CreatedDate,
	    Category,
	    ContentSize,
		ContentType
	FROM   adn_DocumentsGlobalized
	WHERE   ItemID = @ItemID AND LCID = @LCID
ELSE
	SELECT
	    FileFriendlyName,
	    FileNameUrl,
	    CreatedByUser,
	    CreatedDate,
	    Category,
	    ContentSize,
		ContentType
	FROM   adn_Documents
	WHERE   ItemID = @ItemID
END
GO

CREATE PROCEDURE [dbo].[adn_GetDocumentContentGlobalized]
(
    @LCID		int,
    @DefLCID	int,
    @ItemID		int
)
AS
BEGIN
IF EXISTS (SELECT 1 FROM adn_DocumentsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
SELECT Content,
    ContentType,
    ContentSize,
    FileFriendlyName,
    FileFriendlyName as [FileName],
    FileNameUrl
FROM adn_DocumentsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID
ELSE
SELECT Content,
    ContentType,
    ContentSize,
    FileFriendlyName,
    FileFriendlyName as [FileName],
    FileNameUrl
FROM adn_Documents WHERE ItemID = @ItemID 
END
GO

CREATE PROCEDURE [dbo].[adn_UpdateDocumentGlobalized]
(
    @LCID				int,
    @DefLCID			int,
    @ItemID				int,
    @ModuleID			int,
    @FileFriendlyName	nvarchar(150),
    @FileNameUrl		nvarchar(250),
    @UserName			nvarchar(100),
    @Category			nvarchar(50),
    @Content			image,
    @ContentType		nvarchar(50),
    @ContentSize		int
)
AS
IF EXISTS (SELECT 1 FROM adn_DocumentsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
BEGIN
IF (@ContentSize=0)
	UPDATE adn_DocumentsGlobalized
	SET CreatedByUser    = @UserName,
		CreatedDate      = GETUTCDATE(),
		Category         = @Category,
		FileFriendlyName = @FileFriendlyName,
		ContentType      = @ContentType,
		FileNameUrl      = @FileNameUrl
	WHERE ItemID = @ItemID AND LCID = @LCID
ELSE
	UPDATE adn_DocumentsGlobalized
	SET	CreatedByUser     = @UserName,
		CreatedDate       = GETUTCDATE(),
		Category          = @Category,
		FileFriendlyName  = @FileFriendlyName,
		FileNameUrl       = @FileNameUrl,
		Content           = @Content,
		ContentType       = @ContentType,
		ContentSize       = @ContentSize
	WHERE ItemID = @ItemID AND LCID = @LCID
END
ELSE
BEGIN
IF ( @LCID = @DefLCID or @ItemID < 1 )
	EXEC adn_UpdateDocument @ItemID,@ModuleID,
		@FileFriendlyName,@FileNameUrl,@UserName,@Category,@Content,@ContentType,@ContentSize
ELSE
	INSERT INTO adn_DocumentsGlobalized
	(
		LCID,
		ItemID,
		ModuleID,
		FileFriendlyName,
		FileNameUrl,
		CreatedByUser,
		CreatedDate,
		Category,
		Content,
		ContentType,
		ContentSize
	)
	VALUES
	(
		@LCID,
		@ItemID,
		@ModuleID,
		@FileFriendlyName,
		@FileNameUrl,
		@UserName,
		GETUTCDATE(),
		@Category,
		@Content,
		@ContentType,
		@ContentSize
	)
END
GO

CREATE PROCEDURE [dbo].[adn_DeleteDocumentGlobalized]
(
    @ItemID int
)
AS
BEGIN TRAN
DELETE FROM adn_Documents WHERE ItemID = @ItemID
IF ( @@error = 0 )
DELETE FROM adn_DocumentsGlobalized WHERE ItemID = @ItemID
IF ( @@error = 0 )
BEGIN
	COMMIT
	RETURN 1
END
ELSE ROLLBACK
RETURN 0
GO

-- FieldLocalizer
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_FieldLocalizer]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_FieldLocalizerDesc] (
	[FieldId]		[int] IDENTITY (1,1) NOT NULL ,
	[PortalId]		[int] NOT NULL ,
	[TypeName] 		nvarchar(100),
	[Fieldname]		nvarchar(200),
	[FieldType]		int,
	[FieldFlags]	int,
	[FieldLenght]	int,	
	[DisplaySize] 	int,
	CONSTRAINT [PK_adn_FieldLocalizerDesc] PRIMARY KEY NONCLUSTERED 
	(
		[FieldId]
	)
)
END
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeleteFieldLocalizerDesc]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteFieldLocalizerDesc]
GO

CREATE PROCEDURE [dbo].[adn_DeleteFieldLocalizerDesc]
(
    @FieldId int
)
AS
DELETE FROM adn_FieldLocalizerDesc WHERE [FieldId] = @FieldId
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetFieldLocalizerDesc]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFieldLocalizerDesc]
GO

CREATE PROCEDURE [dbo].[adn_GetFieldLocalizerDesc]
(
    @FieldId int
)
AS
SELECT * FROM adn_FieldLocalizerDesc WHERE [FieldId]  = @FieldId 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetFieldLocalizerdescByPortal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFieldLocalizerDescByPortal]
GO

CREATE PROCEDURE [dbo].[adn_GetFieldLocalizerDescByPortal]
(
    @PortalId int
)
AS
SELECT * FROM adn_FieldLocalizerDesc WHERE [PortalId] = @PortalId
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetFieldLocalizerdescByEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFieldLocalizerDescByEntity]
GO

CREATE PROCEDURE [dbo].[adn_GetFieldLocalizerDescByEntity]
(
    @PortalId int,
    @TypeName nvarchar(100)
)
AS
SELECT * FROM adn_FieldLocalizerDesc WHERE [PortalId] = @PortalId  AND [TypeName]  = @TypeName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetFieldLocalizerDescByEntityField]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFieldLocalizerDescByEntityField]
GO

CREATE PROCEDURE [dbo].[adn_GetFieldLocalizerDescByEntityField]
(
    @PortalId int,
    @TypeName nvarchar(100),
    @FieldName nvarchar(100)
)
AS
SELECT * FROM adn_FieldLocalizerDesc WHERE [PortalId] = @PortalId  AND [TypeName]  = @TypeName AND [FieldName]  = @FieldName
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateFieldLocalizerDesc]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateFieldLocalizerDesc]
GO

CREATE PROCEDURE [dbo].[adn_UpdateFieldLocalizerDesc]
(
	@FieldId		int OUTPUT,
	@PortalId		int,
	@TypeName 		nvarchar(100),
	@Fieldname		nvarchar(200),
	@FieldType		int,
	@FieldFlags		int,
	@FieldLenght	int,	
	@DisplaySize 	int
)
AS
IF (@FieldId=0) OR NOT EXISTS ( SELECT * FROM adn_FieldLocalizerDesc WHERE FieldId = @FieldId )
	BEGIN
	INSERT INTO adn_FieldLocalizerDesc
	(	
		[PortalId],
		[TypeName],
		[Fieldname],
		[FieldType],
		[FieldFlags],
		[FieldLenght],	
		[DisplaySize]
	)
	VALUES
	(   
		@PortalId,
		@TypeName,
		@Fieldname,
		@FieldType,
		@FieldFlags,
		@FieldLenght,	
		@DisplaySize
	)
	SELECT @FieldId= @@Identity
	END
ELSE
BEGIN
	UPDATE adn_FieldLocalizerDesc
	SET [PortalId]	=	@PortalId,
		[TypeName]	=	@TypeName,
		[Fieldname]	=	@Fieldname,
		[FieldType]	=	@FieldType,
		[FieldFlags]=	@FieldFlags,
		[FieldLenght]=	@FieldLenght,	
		[DisplaySize]=	@DisplaySize
	WHERE FieldId = @FieldId
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_FieldLocalizer]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_FieldLocalizer](
	[FieldId]		[int] NOT NULL ,
	[TypeName] 		nvarchar(100),
	[CrmID]			Uniqueidentifier,
	ShortValue		nvarchar(2000),
	LongValue		nvarchar(max),
CONSTRAINT [PK_adn_FieldLocalizer] PRIMARY KEY NONCLUSTERED 
(
	[FieldId] ASC,
	[CrmID]
) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] )
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_FieldLocalizerGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_FieldLocalizerGlobalized](
	[FieldId]		[int] NOT NULL ,
	[LCID]			[int] NOT NULL,
	[TypeName] 		nvarchar(100),
	[CrmID]			Uniqueidentifier,
	ShortValue		nvarchar(2000),
	LongValue		nvarchar(max),
CONSTRAINT [PK_adn_FieldLocalizerGlobalized] PRIMARY KEY NONCLUSTERED 
(
	[LCID] ASC,
	[FieldId] ASC,
	[CrmID]
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
CONSTRAINT [FK_adn_FieldLocalizerGlobalized_adn_FieldLocalizer] FOREIGN KEY 
	(
		[FieldId],
		[CrmID]
	) REFERENCES [dbo].[adn_FieldLocalizer] 
	(
		[FieldId],
		[CrmID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO


IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetFieldLocalizerByPortal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFieldLocalizerByPortal]
GO

CREATE PROCEDURE [dbo].[adn_GetFieldLocalizerByPortal]
(
	@PortalId		int
)
AS
BEGIN
SELECT d.PortalId,f.*, d.Fieldname, d.FieldType,d.FieldFlags, d.FieldLenght, d.DisplaySize
FROM adn_FieldLocalizer f INNER JOIN  adn_FieldLocalizerDesc d ON f.FieldId= d.FieldId WHERE d.[PortalId] = @PortalId
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetFieldLocalizerGlobalizedByPortal]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFieldLocalizerGlobalizedByPortal]
GO

CREATE PROCEDURE [dbo].[adn_GetFieldLocalizerGlobalizedByPortal]
(
    @LCID		int,
    @DefLCID	int,
	@PortalId		int
)
AS
SELECT d.PortalId,f.FieldId,f.TypeName,f.CrmID,f.ShortValue,f.LongValue,
		d.Fieldname, d.FieldType,d.FieldFlags, d.FieldLenght, d.DisplaySize
FROM adn_FieldLocalizerGlobalized f INNER JOIN  adn_FieldLocalizerDesc d ON f.FieldId= d.FieldId 
	WHERE d.[PortalId] = @PortalId AND LCID = @LCID 
UNION
SELECT d.PortalId,f.FieldId,f.TypeName,f.CrmID,f.ShortValue,f.LongValue,
		d.Fieldname, d.FieldType,d.FieldFlags, d.FieldLenght, d.DisplaySize
FROM adn_FieldLocalizer f INNER JOIN  adn_FieldLocalizerDesc d ON f.FieldId= d.FieldId 
WHERE d.[PortalId] = @PortalId 
	AND NOT f.CrmID IN (SELECT CrmID FROM adn_FieldLocalizerGlobalized WHERE d.[PortalId] = @PortalId  AND LCID = @LCID) 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetFieldLocalizerByEntityAll]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFieldLocalizerByEntityAll]
GO

CREATE PROCEDURE [dbo].[adn_GetFieldLocalizerByEntityAll]
(
	@TypeName	nvarchar(100)
)
AS
BEGIN
SELECT f.*, d.Fieldname, d.FieldType,d.FieldFlags, d.FieldLenght, d.DisplaySize
FROM adn_FieldLocalizer f INNER JOIN  adn_FieldLocalizerDesc d ON f.FieldId= d.FieldId WHERE f.[TypeName] = @TypeName 
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetFieldLocalizerGlobalizedByEntityAll]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFieldLocalizerGlobalizedByEntityAll]
GO

CREATE PROCEDURE [dbo].[adn_GetFieldLocalizerGlobalizedByEntityAll]
(
    @LCID		int,
    @DefLCID	int,
	@TypeName	nvarchar(100)
)
AS

BEGIN
IF EXISTS (SELECT 1 FROM adn_FieldLocalizerGlobalized WHERE [TypeName] = @TypeName AND LCID = @LCID)
SELECT f.FieldId,f.TypeName,f.CrmID,f.ShortValue,f.LongValue,
		d.Fieldname, d.FieldType,d.FieldFlags, d.FieldLenght, d.DisplaySize
FROM adn_FieldLocalizerGlobalized f INNER JOIN  adn_FieldLocalizerDesc d ON f.FieldId= d.FieldId 
	WHERE f.[TypeName] = @TypeName AND LCID = @LCID 
UNION
SELECT f.FieldId,f.TypeName,f.CrmID,f.ShortValue,f.LongValue,
		d.Fieldname, d.FieldType,d.FieldFlags, d.FieldLenght, d.DisplaySize
FROM adn_FieldLocalizer f INNER JOIN  adn_FieldLocalizerDesc d ON f.FieldId= d.FieldId 
WHERE f.[TypeName] = @TypeName 
	AND NOT f.CrmID IN (SELECT CrmID FROM adn_FieldLocalizerGlobalized WHERE [TypeName] = @TypeName  AND LCID = @LCID) 
ELSE 
EXEC adn_GetFieldLocalizerByEntityAll @TypeName
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetFieldLocalizerByEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFieldLocalizerByEntity]
GO

CREATE PROCEDURE [dbo].[adn_GetFieldLocalizerByEntity]
(
	@TypeName	nvarchar(100),
    @CrmID		uniqueidentifier
)
AS
BEGIN
SELECT f.*, d.Fieldname, d.FieldType,d.FieldFlags, d.FieldLenght, d.DisplaySize
FROM adn_FieldLocalizer f INNER JOIN  adn_FieldLocalizerDesc d ON f.FieldId= d.FieldId WHERE f.[TypeName] = @TypeName AND f.[CrmID]= @CrmID 
END
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetFieldLocalizerGlobalizedByEntity]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFieldLocalizerGlobalizedByEntity]
GO

CREATE PROCEDURE [dbo].[adn_GetFieldLocalizerGlobalizedByEntity]
(
    @LCID		int,
    @DefLCID	int,
	@TypeName	nvarchar(100),
    @CrmID		uniqueidentifier
)
AS

BEGIN
IF EXISTS (SELECT 1 FROM adn_FieldLocalizerGlobalized WHERE [TypeName] = @TypeName AND [CrmID]= @CrmID AND LCID = @LCID)
SELECT f.FieldId,f.TypeName,f.CrmID,f.ShortValue,f.LongValue,
		d.Fieldname, d.FieldType,d.FieldFlags, d.FieldLenght, d.DisplaySize
FROM adn_FieldLocalizerGlobalized f INNER JOIN  adn_FieldLocalizerDesc d ON f.FieldId= d.FieldId 
	WHERE f.[TypeName] = @TypeName AND f.[CrmID]= @CrmID AND LCID = @LCID 
UNION
SELECT f.FieldId,f.TypeName,f.CrmID,f.ShortValue,f.LongValue,
		d.Fieldname, d.FieldType,d.FieldFlags, d.FieldLenght, d.DisplaySize
FROM adn_FieldLocalizer f INNER JOIN  adn_FieldLocalizerDesc d ON f.FieldId= d.FieldId 
WHERE f.[TypeName] = @TypeName AND f.[CrmID]= @CrmID 
	AND NOT f.CrmID IN (SELECT @CrmID FROM adn_FieldLocalizerGlobalized WHERE [TypeName] = @TypeName AND [CrmID]= @CrmID AND LCID = @LCID) 
ELSE 
EXEC adn_GetFieldLocalizerByEntity @TypeName,@CrmID
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleFieldLocalizerGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleFieldLocalizerGlobalized]
GO

CREATE PROCEDURE [dbo].[adn_GetSingleFieldLocalizerGlobalized]
(
    @LCID		int,
    @DefLCID	int,
	@FieldId	int,
	@TypeName	nvarchar(100),
    @CrmID		uniqueidentifier
)
AS
BEGIN
IF EXISTS (SELECT 1 FROM adn_FieldLocalizerGlobalized WHERE [FieldId]=@FieldId AND [TypeName] = @TypeName AND [CrmID]= @CrmID AND LCID = @LCID)
	SELECT [FieldId],[TypeName],[CrmID],ShortValue,LongValue FROM adn_FieldLocalizerGlobalized
		WHERE [FieldId]=@FieldId AND [TypeName] = @TypeName AND [CrmID]= @CrmID AND LCID = @LCID
ELSE
	SELECT [FieldId],[TypeName],[CrmID],ShortValue,LongValue FROM adn_FieldLocalizer
		WHERE [FieldId]=@FieldId AND [TypeName] = @TypeName AND [CrmID]= @CrmID 
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateFieldLocalizer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateFieldLocalizer]
GO

CREATE PROCEDURE [dbo].[adn_UpdateFieldLocalizer]
(
	@FieldId	int,
	@TypeName	nvarchar(100),
    @CrmID		uniqueidentifier,
	@ShortValue nvarchar(2000),
	@LongValue  nvarchar(max)   
)
AS
IF EXISTS (SELECT 1 FROM adn_FieldLocalizer WHERE [FieldId]=@FieldId AND [TypeName] = @TypeName AND [CrmID]= @CrmID )
BEGIN
	UPDATE adn_FieldLocalizer
		SET 	ShortValue=@ShortValue,
				LongValue=@LongValue
	WHERE [FieldId]=@FieldId AND [TypeName] = @TypeName AND [CrmID]= @CrmID 
END
ELSE
BEGIN
	INSERT INTO adn_FieldLocalizer
	(
		[FieldId],[TypeName],[CrmID],ShortValue,LongValue 
	)
	VALUES
	(	@FieldId,@TypeName,@CrmID,@ShortValue,@LongValue)
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateFieldLocalizerGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateFieldLocalizerGlobalized]
GO

CREATE PROCEDURE [dbo].[adn_UpdateFieldLocalizerGlobalized]
(
    @LCID		int,
    @DefLCID	int,
	@FieldId	int,
	@TypeName	nvarchar(100),
    @CrmID		uniqueidentifier,
	@ShortValue nvarchar(2000),
	@LongValue  nvarchar(max)   
)
AS
IF EXISTS (SELECT 1 FROM adn_FieldLocalizerGlobalized WHERE [FieldId]=@FieldId AND [TypeName] = @TypeName AND [CrmID]= @CrmID AND LCID = @LCID )
BEGIN
	UPDATE adn_FieldLocalizerGlobalized
		SET 	ShortValue=@ShortValue,
				LongValue=@LongValue
	WHERE [FieldId]=@FieldId AND [TypeName] = @TypeName AND [CrmID]= @CrmID AND LCID = @LCID
END
ELSE
BEGIN
IF ( @LCID = @DefLCID )
	EXEC adn_UpdateFieldLocalizer @FieldId,@TypeName,@CrmID,@ShortValue,@LongValue
ELSE
	INSERT INTO adn_FieldLocalizerGlobalized
	(
		LCID,[FieldId],[TypeName],[CrmID],ShortValue,LongValue 
	)
	VALUES
	(	@LCID,@FieldId,@TypeName,@CrmID,@ShortValue,@LongValue	)
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteFieldLocalizer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteFieldLocalizer]
GO

CREATE PROCEDURE [dbo].[adn_DeleteFieldLocalizer]
(
	@FieldId	int,
	@TypeName	nvarchar(100),
    @CrmID		uniqueidentifier
)
AS
DELETE FROM adn_FieldLocalizer WHERE [FieldId]=@FieldId AND [TypeName] = @TypeName AND [CrmID]= @CrmID 
IF ( @@error = 0 )
	RETURN 1
RETURN 0
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteFieldLocalizerGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteFieldLocalizerGlobalized]
GO

CREATE PROCEDURE [dbo].[adn_DeleteFieldLocalizerGlobalized]
(
    @LCID		int,
    @DefLCID	int,
	@FieldId	int,
	@TypeName	nvarchar(100),
    @CrmID		uniqueidentifier
)
AS
IF EXISTS (SELECT 1 FROM adn_FieldLocalizerGlobalized WHERE [FieldId]=@FieldId AND [TypeName] = @TypeName AND [CrmID]= @CrmID AND LCID = @LCID )
BEGIN 
	DELETE FROM adn_FieldLocalizerGlobalized
	WHERE [FieldId]=@FieldId AND [TypeName] = @TypeName AND [CrmID]= @CrmID 
	IF NOT ( @@error = 0 )
		RETURN 0
	RETURN 1
END
ELSE
EXEC adn_DeleteFieldLocalizer @FieldId,@TypeName,@CrmID
GO

-- Announcements
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddAnnouncement]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddAnnouncement]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAnnouncements]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAnnouncements]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAnnouncementsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAnnouncementsGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateAnnouncement]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateAnnouncement]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateAnnouncementGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateAnnouncementGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteAnnouncementGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteAnnouncementGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleAnnouncementGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleAnnouncementGlobalized]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_Announcements]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_Announcements] (
	[ItemID] [int]  IDENTITY (1, 1) NOT NULL ,
	[ModuleID] [int] NOT NULL ,
	[CreatedByUser] [nvarchar] (100) NULL ,
	[CreatedDate] [datetime] NULL ,
	[Title] [nvarchar] (250) NULL ,
	[MoreLink] [nvarchar] (150) NULL ,
	[ExpireDate] [datetime] NULL ,
	[Description] [nvarchar] (max) NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_Announcements] ADD 
	CONSTRAINT [PK_adn_Announcements] PRIMARY KEY NONCLUSTERED 
	(
		[ItemID]
	)  ON [PRIMARY] 

ALTER TABLE [dbo].[adn_Announcements] ADD 
	CONSTRAINT [FK_adn_Announcements_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AnnouncementsGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_AnnouncementsGlobalized] (
	[LCID]		[int] NOT NULL,
	[ItemID] [int] NOT NULL ,
	[ModuleID] [int] NOT NULL ,
	[CreatedByUser] [nvarchar] (100) NULL ,
	[CreatedDate] [datetime] NULL ,
	[Title] [nvarchar] (250) NULL ,
	[MoreLink] [nvarchar] (150) NULL ,
	[ExpireDate] [datetime] NULL ,
	[Description] [nvarchar] (max) NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_AnnouncementsGlobalized] ADD 
	CONSTRAINT [PK_adn_AnnouncementsGlobalized] PRIMARY KEY NONCLUSTERED 
	(
		[LCID],
		[ItemID]
	)  ON [PRIMARY] 

ALTER TABLE [dbo].[adn_AnnouncementsGlobalized] ADD 
	CONSTRAINT [FK_adn_AnnouncementsGlobalized_adn_Announcements] FOREIGN KEY 
	(
		[ItemID]
	) REFERENCES [dbo].[adn_Announcements] (
		[ItemID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 

ALTER TABLE [dbo].[adn_AnnouncementsGlobalized] ADD 
	CONSTRAINT [FK_adn_AnnouncementsGlobalized_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE NO ACTION NOT FOR REPLICATION 
END
GO


CREATE PROCEDURE [dbo].[adn_AddAnnouncement]
(
    @ModuleID       int,
    @UserName       nvarchar(100),
    @Title          nvarchar(250),
    @MoreLink       nvarchar(150),
    @ExpireDate     DateTime,
    @Description    nvarchar(max),
    @ItemID         int OUTPUT
)
AS
INSERT INTO adn_Announcements
(
    ModuleID,
    CreatedByUser,
    CreatedDate,
    Title,
    MoreLink,
    ExpireDate,
    Description
)
VALUES
(
    @ModuleID,
    @UserName,
    GETUTCDATE(),
    @Title,
    @MoreLink,
    @ExpireDate,
    @Description
)
SELECT @ItemID = @@Identity
GO

-- 24/12
CREATE PROCEDURE [dbo].[adn_GetAnnouncements]
(
    @ModuleID int
)
AS
IF ( @ModuleID = 0 )
	SELECT ItemID,
		CreatedByUser,
		CreatedDate,
		Title,
		MoreLink,
		ExpireDate,
		Description
	FROM adn_Announcements
	WHERE ExpireDate > GETUTCDATE()
	ORDER BY CreatedDate DESC
ELSE
	SELECT ItemID,
		CreatedByUser,
		CreatedDate,
		Title,
		MoreLink,
		ExpireDate,
		Description
	FROM adn_Announcements
	WHERE ModuleID = @ModuleID
	  AND ExpireDate > GETUTCDATE()
	ORDER BY CreatedDate DESC
GO

CREATE PROCEDURE [dbo].[adn_UpdateAnnouncement]
(
    @ItemID         int,
    @UserName       nvarchar(100),
    @Title          nvarchar(250),
    @MoreLink       nvarchar(150),
    @ExpireDate     datetime,
    @Description    nvarchar(max)
)
AS

UPDATE adn_Announcements
SET CreatedByUser   = @UserName,
    CreatedDate     = GETUTCDATE(),
    Title           = @Title,
    MoreLink        = @MoreLink,
    ExpireDate      = @ExpireDate,
    Description     = @Description
WHERE ItemID = @ItemID
GO

-- 24/12
CREATE PROCEDURE [dbo].[adn_GetAnnouncementsGlobalized]
(
    @LCID			int,
    @DefLCID		int,
    @ModuleID		int
)
AS
IF ( @ModuleID = 0 )
BEGIN
	IF EXISTS (SELECT 1 FROM adn_AnnouncementsGlobalized WHERE LCID = @LCID)
	SELECT ItemID,
		CreatedByUser,
		CreatedDate,
		Title,
		MoreLink,
		ExpireDate,
		Description
	FROM adn_AnnouncementsGlobalized
	WHERE LCID = @LCID
	  AND ExpireDate > GETUTCDATE()
	UNION
	SELECT ItemID,
		CreatedByUser,
		CreatedDate,
		Title,
		MoreLink,
		ExpireDate,
		Description
	FROM adn_Announcements
	WHERE ExpireDate > GETUTCDATE()
	AND NOT itemid IN (SELECT ItemID FROM adn_AnnouncementsGlobalized WHERE LCID = @LCID)
	ORDER BY CreatedDate DESC
	ELSE 
	EXEC adn_GetAnnouncements @ModuleID
END
ELSE
BEGIN
	IF EXISTS (SELECT 1 FROM adn_AnnouncementsGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
	SELECT ItemID,
		CreatedByUser,
		CreatedDate,
		Title,
		MoreLink,
		ExpireDate,
		Description
	FROM adn_AnnouncementsGlobalized
	WHERE ModuleID = @ModuleID AND LCID = @LCID
	  AND ExpireDate > GETUTCDATE()
	UNION
	SELECT ItemID,
		CreatedByUser,
		CreatedDate,
		Title,
		MoreLink,
		ExpireDate,
		Description
	FROM adn_Announcements
	WHERE ModuleID = @ModuleID AND ExpireDate > GETUTCDATE()
	AND NOT itemid IN (SELECT ItemID FROM adn_AnnouncementsGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
	ORDER BY CreatedDate DESC
	ELSE 
	EXEC adn_GetAnnouncements @ModuleID
END

GO

CREATE PROCEDURE [dbo].[adn_UpdateAnnouncementGlobalized]
(
	@LCID int,
	@DefLCID int,
    @ItemID         int,
    @ModuleID		int,
    @UserName       nvarchar(100),
    @Title          nvarchar(250),
    @MoreLink       nvarchar(150),
    @ExpireDate     datetime,
    @Description    nvarchar(max)
)
AS
IF EXISTS (SELECT 1 FROM adn_AnnouncementsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
UPDATE adn_AnnouncementsGlobalized
SET CreatedByUser   = @UserName,
    CreatedDate     = GETUTCDATE(),
    Title           = @Title,
    MoreLink        = @MoreLink,
    ExpireDate      = @ExpireDate,
    Description     = @Description
WHERE   ItemID = @ItemID AND LCID = @LCID
ELSE
BEGIN
IF ( @LCID = @DefLCID )
	EXEC adn_UpdateAnnouncement @ItemID,@UserName,@Title,@MoreLink,@ExpireDate,@Description
ELSE
INSERT INTO adn_AnnouncementsGlobalized
(
    LCID,
    ItemID,
    ModuleID,
    CreatedByUser,
    CreatedDate,
    Title,
    MoreLink,
    ExpireDate,
    Description
)
VALUES
(
    @LCID,
    @ItemID,
    @ModuleID,
    @UserName,
    GETUTCDATE(),
    @Title,
    @MoreLink,
    @ExpireDate,
    @Description
)
END
GO

CREATE PROCEDURE [dbo].[adn_DeleteAnnouncementGlobalized]
(
    @ItemID int
)
AS
BEGIN TRAN
DELETE FROM adn_Announcements WHERE ItemID = @ItemID
IF ( @@error = 0 )
DELETE FROM adn_AnnouncementsGlobalized WHERE ItemID = @ItemID
IF ( @@error = 0 )
BEGIN
	COMMIT
	RETURN 1
	END
ELSE ROLLBACK
RETURN 0
GO

CREATE PROCEDURE [dbo].[adn_GetSingleAnnouncementGlobalized]
(
	@LCID		int,
	@DefLCID	int,
    @ItemID		int
)
AS
IF EXISTS (SELECT 1 FROM adn_AnnouncementsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
SELECT
    CreatedByUser,
    CreatedDate,
    Title,
    MoreLink,
    ExpireDate,
    Description
FROM  adn_AnnouncementsGlobalized
WHERE ItemID = @ItemID AND LCID = @LCID
ELSE
SELECT
CreatedByUser,
CreatedDate,
Title,
MoreLink,
ExpireDate,
Description
FROM  adn_Announcements WHERE  ItemID = @ItemID
GO

-- HtmlModule

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_HtmlText]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_HtmlText] (
	[ModuleID] [int] NOT NULL ,
	[DesktopHtml] [nvarchar] (max) NOT NULL ,
	CONSTRAINT [PK_adn_HtmlText] PRIMARY KEY NONCLUSTERED 
	(
		[ModuleID]
	),
	CONSTRAINT [FK_adn_HtmlText_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
)
END
GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_HtmlTextGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_HtmlTextGlobalized] (
	[LCID]		[int] NOT NULL,
	[ModuleID] [int] NOT NULL ,
	[DesktopHtml] [nvarchar] (max) NOT NULL ,
	CONSTRAINT [PK_adn_HtmlTextGlobalized] PRIMARY KEY NONCLUSTERED 
	(
		[LCID],
		[ModuleID]
	),
	CONSTRAINT [FK_adn_HtmlTextGlobalized_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
)
END
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetHtmlText]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetHtmlText]
GO

CREATE PROCEDURE [dbo].[adn_GetHtmlText]
(
    @ModuleID int
)
AS
SELECT * FROM adn_HtmlText WHERE ModuleID = @ModuleID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetHtmlTextGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetHtmlTextGlobalized]
GO

CREATE PROCEDURE [dbo].[adn_GetHtmlTextGlobalized]
(
    @LCID			int,
    @DefLCID		int,
    @ModuleID		int
)
AS
IF EXISTS (SELECT 1 FROM adn_HtmlTextGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
SELECT * FROM adn_HtmlTextGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID
ELSE 
EXEC adn_GetHtmlText @ModuleID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateHtmlText]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateHtmlText]
GO

CREATE   PROCEDURE [dbo].[adn_UpdateHtmlText]
(
    @ModuleID      int,
    @DesktopHtml   [nvarchar] (max) 
)
AS
IF NOT EXISTS ( SELECT * FROM adn_HtmlText WHERE ModuleID = @ModuleID )
INSERT INTO adn_HtmlText 
(
    ModuleID,
    DesktopHtml
) 
VALUES (
    @ModuleID,
    @DesktopHtml
)
ELSE
UPDATE adn_HtmlText 
SET DesktopHtml   = @DesktopHtml
WHERE ModuleID = @ModuleID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateHtmlTextGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateHtmlTextGlobalized]
GO

CREATE   PROCEDURE [dbo].[adn_UpdateHtmlTextGlobalized]
(
    @LCID			int,
    @DefLCID		int,
    @ModuleID      int,
    @DesktopHtml   [nvarchar] (max) 
)
AS
IF EXISTS (SELECT 1 FROM adn_HtmlTextGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
UPDATE adn_HtmlTextGlobalized
SET DesktopHtml   = @DesktopHtml
WHERE ModuleID = @ModuleID AND LCID = @LCID
ELSE
BEGIN
IF ( @LCID = @DefLCID )
	EXEC adn_UpdateHtmlText @ModuleID, @DesktopHtml
ELSE
INSERT INTO adn_HtmlTextGlobalized 
(
	LCID,
    ModuleID,
    DesktopHtml
) 
VALUES 
(
	@LCID,
    @ModuleID,
    @DesktopHtml
)
END
GO


-- HtmlTabs

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddHtmlTab]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddHtmlTab]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetHtmlTabs]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetHtmlTabs]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetHtmlTabsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetHtmlTabsGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateHtmlTab]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateHtmlTab]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateHtmlTabOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateHtmlTabOrder]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateHtmlTabGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateHtmlTabGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateHtmlTabOrderGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateHtmlTabOrderGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteHtmlTabGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteHtmlTabGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleHtmlTabGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleHtmlTabGlobalized]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_HtmlTabs]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_HtmlTabs] (
	[ItemID]		[int]  IDENTITY (1, 1) NOT NULL ,
	[ModuleID]		[int] NOT NULL ,
	[TabOrder]		[int] NOT NULL ,
	[CreatedDate]	[datetime] NULL ,
	[Title]			[nvarchar] (250) NULL ,
	[IsBreak]		[bit] NOT NULL,
	[Description]	[nvarchar] (max) NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_HtmlTabs] ADD 
	CONSTRAINT [PK_adn_HtmlTabs] PRIMARY KEY NONCLUSTERED 
	(
		[ItemID]
	)  ON [PRIMARY] 

ALTER TABLE [dbo].[adn_HtmlTabs] ADD 
	CONSTRAINT [FK_adn_HtmlTabs_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_HtmlTabsGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_HtmlTabsGlobalized] (
	[LCID]			[int] NOT NULL,
	[ItemID]		[int] NOT NULL ,
	[ModuleID]		[int] NOT NULL ,
	[TabOrder]		[int] NOT NULL ,
	[CreatedDate]	[datetime] NULL ,
	[Title]			[nvarchar] (250) NULL ,
	[IsBreak]		[bit] NOT NULL ,
	[Description]	[nvarchar] (max) NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_HtmlTabsGlobalized] ADD 
	CONSTRAINT [PK_adn_HtmlTabsGlobalized] PRIMARY KEY NONCLUSTERED 
	(
		[LCID],
		[ItemID]
	)  ON [PRIMARY] 

ALTER TABLE [dbo].[adn_HtmlTabsGlobalized] ADD 
	CONSTRAINT [FK_adn_HtmlTabsGlobalized_adn_HtmlTabs] FOREIGN KEY 
	(
		[ItemID]
	) REFERENCES [dbo].[adn_HtmlTabs] (
		[ItemID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 

ALTER TABLE [dbo].[adn_HtmlTabsGlobalized] ADD 
	CONSTRAINT [FK_adn_HtmlTabsGlobalized_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE NO ACTION NOT FOR REPLICATION 
END
GO


CREATE PROCEDURE [dbo].[adn_AddHtmlTab]
(
    @ModuleID       int,
    @Title          nvarchar(250),
    @IsBreak        bit,
    @Description    nvarchar(max),
	@TabOrder		int,
    @ItemID         int OUTPUT
)
AS
INSERT INTO adn_HtmlTabs
(
    ModuleID,
	TabOrder,
    CreatedDate,
    Title,
    IsBreak,
    Description
)
VALUES
(
    @ModuleID,
	@TabOrder,
    GETUTCDATE(),
    @Title,
    @IsBreak,
    @Description
)
SELECT @ItemID = @@Identity
GO

CREATE PROCEDURE [dbo].[adn_GetHtmlTabs]
(
    @ModuleID int
)
AS
IF ( @ModuleID = 0 )
	SELECT ItemID,
		ModuleID,
		TabOrder,
		CreatedDate,
		Title,
		IsBreak,
		Description
	FROM adn_HtmlTabs ORDER BY TabOrder ASC
ELSE
	SELECT ItemID,
		ModuleID,
		TabOrder,
		CreatedDate,
		Title,
		IsBreak,
		Description
	FROM adn_HtmlTabs WHERE ModuleID = @ModuleID ORDER BY TabOrder ASC
GO

CREATE PROCEDURE [dbo].[adn_UpdateHtmlTab]
(
    @ItemID         int,
	@TabOrder		int,
    @Title          nvarchar(250),
    @IsBreak		bit,
    @Description    nvarchar(max)
)
AS
UPDATE adn_HtmlTabs
SET CreatedDate     = GETUTCDATE(),
	TabOrder		= @TabOrder,
    Title           = @Title,
    IsBreak			= @IsBreak,
    Description     = @Description
WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_UpdateHtmlTabOrder]
(
    @ItemID         int,
	@TabOrder		int
)
AS
UPDATE adn_HtmlTabs SET TabOrder = @TabOrder WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_GetHtmlTabsGlobalized]
(
    @LCID			int,
    @DefLCID		int,
    @ModuleID		int
)
AS
IF ( @ModuleID = 0 )
BEGIN
	IF EXISTS (SELECT 1 FROM adn_HtmlTabsGlobalized WHERE LCID = @LCID)
	SELECT ItemID,
		ModuleID,
		TabOrder,
		CreatedDate,
		Title,
		IsBreak,
		Description
	FROM adn_HtmlTabsGlobalized	WHERE LCID = @LCID 
	UNION
	SELECT ItemID,
		ModuleID,
		TabOrder,
		CreatedDate,
		Title,
		IsBreak,
		Description
	FROM adn_HtmlTabs
	WHERE NOT itemid IN (SELECT ItemID FROM adn_HtmlTabsGlobalized WHERE LCID = @LCID)
	ORDER BY TabOrder ASC
	ELSE 
	EXEC adn_GetHtmlTabs @ModuleID
END
ELSE
BEGIN
	IF EXISTS (SELECT 1 FROM adn_HtmlTabsGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
	SELECT ItemID,
		ModuleID,
		TabOrder,
		CreatedDate,
		Title,
		IsBreak,
		Description
	FROM adn_HtmlTabsGlobalized	WHERE ModuleID = @ModuleID AND LCID = @LCID
	UNION
	SELECT ItemID,
		ModuleID,
		TabOrder,
		CreatedDate,
		Title,
		IsBreak,
		Description
	FROM adn_HtmlTabs WHERE ModuleID = @ModuleID 
	AND NOT itemid IN (SELECT ItemID FROM adn_HtmlTabsGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
	ORDER BY TabOrder ASC
	ELSE 
	EXEC adn_GetHtmlTabs @ModuleID
END

GO

CREATE PROCEDURE [dbo].[adn_UpdateHtmlTabGlobalized]
(
	@LCID int,
	@DefLCID int,
    @ItemID         int,
    @ModuleID		int,
    @TabOrder		int,
    @Title          nvarchar(250),
    @IsBreak		bit,
    @Description    nvarchar(max)
)
AS
IF EXISTS (SELECT 1 FROM adn_HtmlTabsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
UPDATE adn_HtmlTabsGlobalized
SET CreatedDate     = GETUTCDATE(),
	TabOrder		= @TabOrder,
    Title           = @Title,
    IsBreak			= @IsBreak,
    Description     = @Description
WHERE ItemID = @ItemID AND LCID = @LCID
ELSE
BEGIN
IF ( @LCID = @DefLCID )
	EXEC adn_UpdateHtmlTab @ItemID,@TabOrder,@Title,@IsBreak,@Description
ELSE
INSERT INTO adn_HtmlTabsGlobalized
(
    LCID,
    ItemID,
    ModuleID,
	TabOrder,
    CreatedDate,
    Title,
    IsBreak,
    Description
)
VALUES
(
    @LCID,
    @ItemID,
    @ModuleID,
	@TabOrder,
    GETUTCDATE(),
    @Title,
    @IsBreak,
    @Description
)
END
GO

CREATE PROCEDURE [dbo].[adn_UpdateHtmlTabOrderGlobalized]
(
	@LCID int,
	@DefLCID int,
    @ItemID         int,
    @ModuleID		int,
    @TabOrder		int
)
AS
IF EXISTS (SELECT 1 FROM adn_HtmlTabsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
UPDATE adn_HtmlTabsGlobalized
SET TabOrder		= @TabOrder
WHERE ItemID = @ItemID AND LCID = @LCID
ELSE
EXEC adn_UpdateHtmlTabOrder @ItemID,@TabOrder
GO

CREATE PROCEDURE [dbo].[adn_DeleteHtmlTabGlobalized]
(
    @ItemID int
)
AS
BEGIN TRAN
DELETE FROM adn_HtmlTabs WHERE ItemID = @ItemID
IF ( @@error = 0 )
DELETE FROM adn_HtmlTabsGlobalized WHERE ItemID = @ItemID
IF ( @@error = 0 )
BEGIN
	COMMIT
	RETURN 1
	END
ELSE ROLLBACK
RETURN 0
GO

CREATE PROCEDURE [dbo].[adn_GetSingleHtmlTabGlobalized]
(
	@LCID		int,
	@DefLCID	int,
    @ItemID		int
)
AS
IF EXISTS (SELECT 1 FROM adn_HtmlTabsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
SELECT 	TabOrder,
    CreatedDate,
    Title,
    IsBreak,
    Description
FROM  adn_HtmlTabsGlobalized
WHERE ItemID = @ItemID AND LCID = @LCID
ELSE
SELECT 	TabOrder,
	CreatedDate,
	Title,
	IsBreak,
	Description
	FROM  adn_HtmlTabs WHERE  ItemID = @ItemID
GO


-- Rating
-- 28/12

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetRatingGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetRatingGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateRating]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateRating]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateRatingCrmID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateRatingCrmID]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateRatingGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateRatingGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteRatingGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteRatingGlobalized]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_Rating]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_Rating] (
	[ModuleID]		[int] NOT NULL ,
	[CreatedDate]	[datetime] NULL ,
	[StarNumber]	[int] NOT NULL ,
	[CrmCampaignID]	[uniqueidentifier] NULL ,
	[CrmID]			[uniqueidentifier] NULL ,
	[CrmEntityName]	[nvarchar] (100) NULL,
	[Title]			[nvarchar] (250) NULL, 
	[Description]	[nvarchar] (max) NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_Rating] ADD 
	CONSTRAINT [PK_adn_Rating] PRIMARY KEY NONCLUSTERED 
	(
		[ModuleID]
	)  ON [PRIMARY] 

ALTER TABLE [dbo].[adn_Rating] ADD 
	CONSTRAINT [FK_adn_Rating_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_RatingGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_RatingGlobalized] (
	[LCID]			[int] NOT NULL,
	[ModuleID]		[int] NOT NULL ,
	[Title]			[nvarchar] (250) NULL, 
	[Description]	[nvarchar] (max) NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_RatingGlobalized] ADD 
	CONSTRAINT [PK_adn_RatingGlobalized] PRIMARY KEY NONCLUSTERED 
	(
		[LCID],
		[ModuleID]
	)  ON [PRIMARY] 

ALTER TABLE [dbo].[adn_RatingGlobalized] ADD 
	CONSTRAINT [FK_adn_RatingDetail_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Rating] (
		[ModuleID]
	) ON DELETE CASCADE NOT FOR REPLICATION 
END
GO

-- Item Detail tables
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_RatingDetails]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_RatingDetails] (
	[ItemID]		[int]  IDENTITY (1, 1) NOT NULL ,
	[ModuleID]		[int] NOT NULL ,
	[ItemOrder]		[int] NOT NULL ,
	[CrmEntityID]	[uniqueidentifier] NULL ,
	[CrmCampaignID]	[uniqueidentifier] NULL ,
	[CrmID]			[uniqueidentifier] NULL ,
	[CrmImageID]	[uniqueidentifier] NULL ,
	[Title]			[nvarchar] (250) NULL ,
	[Description]	[nvarchar] (max) NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_RatingDetails] ADD 
	CONSTRAINT [PK_adn_RatingDetails] PRIMARY KEY NONCLUSTERED 
	(
		[ItemID]
	)  ON [PRIMARY] 

ALTER TABLE [dbo].[adn_RatingDetails] ADD 
	CONSTRAINT [FK_adn_RatingDetails_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Rating] (
		[ModuleID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_RatingDetailsGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_RatingDetailsGlobalized] (
	[LCID]			[int] NOT NULL,
	[ItemID]		[int] NOT NULL ,
	[Title]			[nvarchar] (250) NULL ,
	[Description]	[nvarchar] (max) NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_RatingDetailsGlobalized] ADD 
	CONSTRAINT [PK_adn_RatingDetailsGlobalized] PRIMARY KEY NONCLUSTERED 
	(
		[LCID],
		[ItemID]
	)  ON [PRIMARY] 

ALTER TABLE [dbo].[adn_RatingDetailsGlobalized] ADD 
	CONSTRAINT [FK_adn_RatingDetailsGlobalized_adn_RatingDetails] FOREIGN KEY 
	(
		[ItemID]
	) REFERENCES [dbo].[adn_RatingDetails] (
		[ItemID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
END
GO

-- Answer tables
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_RatingAnswer]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_RatingAnswer] (
	[ItemID]		[int]  IDENTITY (1, 1) NOT NULL ,
	[RatingItemID]	[int] NOT NULL,
	[CrmID]			[uniqueidentifier] NULL ,
	[RatingValue]	[float] NOT NULL,	
	[CreatedDate]	[datetime] NOT NULL,
    [IPAddress]		[nvarchar](200) NULL,
    [UserName]		[nvarchar] (100) NULL, 
    [UserId]        [uniqueidentifier] NULL,
    [EMail]			[nvarchar] (100) NULL,
	[Phone]			[nvarchar] (100) NULL,
	[Address]		[nvarchar] (250) NULL,
    [City]			[nvarchar] (100) NULL,
    [Zip]			[nvarchar] (50) NULL,
    [Country]		[nvarchar] (100) NULL,
    [Comments]		[nvarchar] (1000) NULL
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_RatingAnswer] ADD 
	CONSTRAINT [PK_adn_RatingAnswer] PRIMARY KEY NONCLUSTERED 
	(
		[ItemID]
	)  ON [PRIMARY] 

ALTER TABLE [dbo].[adn_RatingAnswer] ADD 
	CONSTRAINT [FK_adn_RatingAnswer_adn_RatingDetails] FOREIGN KEY 
	(
		[RatingItemID]
	) REFERENCES [dbo].[adn_RatingDetails] (
		[ItemID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
END
GO

CREATE PROCEDURE [dbo].[adn_GetRatingGlobalized]
(
	@LCID		int,
	@DefLCID	int,
    @ModuleID   int
)
AS
IF EXISTS (SELECT 1 FROM adn_RatingGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
SELECT r.ModuleID,
    r.CreatedDate,
    g.Title,
    g.Description,
	r.StarNumber,
	r.CrmEntityName,
	r.CrmID,
	r.CrmCampaignID,
	(SELECT COUNT(ItemId) FROM adn_RatingDetails d INNER JOIN adn_Rating r ON d.ModuleID = r.ModuleID WHERE r.ModuleID = @ModuleID ) AS ItemCount
FROM  adn_RatingGlobalized g INNER JOIN adn_Rating r ON r.ModuleID = g.ModuleID
WHERE r.ModuleID = @ModuleID AND LCID = @LCID
ELSE
SELECT ModuleID,
    CreatedDate,
    Title,
    Description,
	StarNumber,
	CrmEntityName,
	CrmID,
	CrmCampaignID,
	(SELECT COUNT(ItemId) FROM adn_RatingDetails d INNER JOIN adn_Rating r ON d.ModuleID = r.ModuleID WHERE r.ModuleID = @ModuleID ) AS ItemCount
	FROM  adn_Rating WHERE ModuleID = @ModuleID
GO

CREATE PROCEDURE [dbo].[adn_UpdateRating]
(
    @ModuleID       int,
    @Title          nvarchar(250),
    @Description    nvarchar(max),
    @CrmEntityName  nvarchar(100),
	@CrmCampaignID [uniqueidentifier],
	@StarNumber		int
)
AS
IF EXISTS (SELECT 1 FROM adn_Rating WHERE ModuleID = @ModuleID )
UPDATE adn_Rating
SET CreatedDate     = GETUTCDATE(),
	CrmEntityName	= @CrmEntityName,
	CrmCampaignID	= @CrmCampaignID,
    Title           = @Title,
    Description		= @Description,
    StarNumber		= @StarNumber
WHERE ModuleID = @ModuleID
ELSE
INSERT INTO adn_Rating
(
    ModuleID,
    CreatedDate,
    Title,
    Description,
	StarNumber,
	CrmEntityName,
	CrmCampaignID 
)
VALUES
(
    @ModuleID,
    GETUTCDATE(),
    @Title,
    @Description,
	@StarNumber,
	@CrmEntityName,
	@CrmCampaignID
)
GO

CREATE PROCEDURE [dbo].[adn_UpdateRatingCrmID]
(
    @ModuleID       int,
	@CrmID			[uniqueidentifier]
)
AS
UPDATE adn_Rating SET CrmID	= @CrmID WHERE ModuleID = @ModuleID
GO

CREATE PROCEDURE [dbo].[adn_UpdateRatingGlobalized]
(
	@LCID int,
	@DefLCID int,
    @ModuleID       int,
    @Title          nvarchar(250),
    @Description    nvarchar(max),
    @CrmEntityName  nvarchar(100),
	@CrmCampaignID	[uniqueidentifier],
	@StarNumber		int
)
AS
IF EXISTS (SELECT 1 FROM adn_RatingGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
BEGIN
	UPDATE adn_RatingGlobalized
	SET Title       = @Title,
		Description	= @Description
	WHERE ModuleID = @ModuleID AND LCID = @LCID
	UPDATE adn_Rating
	SET CreatedDate     = GETUTCDATE(),
		CrmEntityName	= @CrmEntityName,
		CrmCampaignID 	= @CrmCampaignID,
		StarNumber		= @StarNumber
	WHERE ModuleID = @ModuleID
END
ELSE
BEGIN
	IF ( ( @LCID = @DefLCID ) OR NOT EXISTS (SELECT 1 FROM adn_Rating WHERE ModuleID = @ModuleID ) )
		EXEC adn_UpdateRating @ModuleID,@Title,@Description,@CrmEntityName,@CrmCampaignID,@StarNumber
	ELSE
	BEGIN
		INSERT INTO adn_RatingGlobalized
		(
			LCID,
			ModuleID,
			Title,
			Description

		)
		VALUES
		(
			@LCID,
			@ModuleID,
			@Title,
			@Description
		)
		UPDATE adn_Rating
		SET CreatedDate     = GETUTCDATE(),
			CrmEntityName	= @CrmEntityName,
			CrmCampaignID 	= @CrmCampaignID,
			StarNumber		= @StarNumber
		WHERE ModuleID = @ModuleID 
	END
END
GO

CREATE PROCEDURE [dbo].[adn_DeleteRatingGlobalized]
(
    @ModuleID int
)
AS
BEGIN TRAN
DELETE FROM adn_Rating WHERE ModuleID = @ModuleID
IF ( @@error = 0 )
BEGIN
	COMMIT
	RETURN 1
	END
ELSE ROLLBACK
RETURN 0
GO

-- Rating Detail sps
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddRatingDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddRatingDetail]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetRatingDetails]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetRatingDetails]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetRatingDetailsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetRatingDetailsGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateRatingDetail]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateRatingDetail]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateRatingDetailCrmID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateRatingDetailCrmID]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateRatingDetailOrder]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateRatingDetailOrder]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateRatingDetailGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateRatingDetailGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteRatingDetailGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteRatingdetailGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleRatingDetailGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleRatingDetailGlobalized]
GO


CREATE PROCEDURE [dbo].[adn_AddRatingDetail]
(
    @ModuleID       int,
    @Title          nvarchar(250),
    @Description    nvarchar(max),
	@ItemOrder		int,
	@CrmEntityID	uniqueidentifier,
	@CrmCampaignID	uniqueidentifier,
	@CrmImageID		uniqueidentifier,
    @ItemID         int OUTPUT
)
AS
INSERT INTO adn_RatingDetails
(
    ModuleID,
	ItemOrder,
    Title,
    Description,
	CrmEntityID,
	CrmCampaignID,
	CrmImageID
)
VALUES
(
    @ModuleID,
	@ItemOrder,
    @Title,
    @Description,
	@CrmEntityID,
	@CrmCampaignID,
	@CrmImageID
)
SELECT @ItemID = @@Identity
GO

CREATE PROCEDURE [dbo].[adn_GetRatingDetails]
(
    @ModuleID int
)
AS
IF ( @ModuleID = 0 )
	SELECT ItemID,
		ModuleID,
		ItemOrder,
		Title,
		[Description],
		CrmEntityID,
		CrmID,
		CrmCampaignID,
		CrmImageID,
		COALESCE ((SELECT COUNT(a.RatingItemID) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID),0) AS TimesRated,
		COALESCE ((SELECT AVG(a.RatingValue) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID),0) AS AverageRating
	FROM adn_RatingDetails r ORDER BY ItemOrder ASC
ELSE
	SELECT ItemID,
		ModuleID,
		ItemOrder,
		Title,
		[Description],
		CrmEntityID,
		CrmID,
		CrmCampaignID,
		CrmImageID,
		COALESCE ((SELECT COUNT(a.RatingItemID) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID),0) AS TimesRated,
		COALESCE ((SELECT AVG(a.RatingValue) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID),0) AS AverageRating
	FROM adn_RatingDetails r WHERE ModuleID = @ModuleID ORDER BY ItemOrder ASC
GO

CREATE PROCEDURE [dbo].[adn_UpdateRatingDetail]
(
    @ItemID         int,
	@ItemOrder		int,
    @Title          nvarchar(250),
	@CrmEntityID	uniqueidentifier,
	@CrmCampaignID	uniqueidentifier,
	@CrmImageID		uniqueidentifier,
    @Description    nvarchar(max)
)
AS
UPDATE adn_RatingDetails
SET ItemOrder		= @ItemOrder,
    Title           = @Title,
    Description     = @Description,
	CrmCampaignID	= @CrmCampaignID,
	CrmImageID		= @CrmImageID,
	CrmEntityID		= @CrmEntityID
	WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_UpdateRatingdetailCrmID]
(
    @ItemID         int,
	@CrmID			[uniqueidentifier]
)
AS
UPDATE adn_RatingDetails SET CrmID	= @CrmID WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_UpdateRatingDetailOrder]
(
    @ItemID         int,
	@ItemOrder		int
)
AS
UPDATE adn_RatingDetails SET ItemOrder = @ItemOrder WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_GetRatingDetailsGlobalized]
(
    @LCID			int,
    @DefLCID		int,
    @ModuleID		int
)
AS
IF ( @ModuleID = 0 )
BEGIN
	IF EXISTS (SELECT 1 FROM adn_RatingDetailsGlobalized WHERE LCID = @LCID)
	SELECT g.ItemID,
		r.ModuleID,
		r.ItemOrder,
		g.Title,
		g.Description,
		r.CrmEntityID,
		r.CrmID,
		r.CrmCampaignID,
		r.CrmImageID,
		(SELECT COUNT(a.RatingItemID) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID) AS TimesRated,
		(SELECT AVG(a.RatingValue) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID) AS AverageRating
	FROM adn_RatingDetailsGlobalized g INNER JOIN adn_RatingDetails r ON g.ItemID = r.ItemID WHERE g.LCID = @LCID 
	UNION
	SELECT ItemID,
		ModuleID,
		ItemOrder,
		Title,
		[Description],
		CrmEntityID,
		r.CrmID,
		r.CrmCampaignID,
		r.CrmImageID,
		(SELECT COUNT(a.RatingItemID) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID) AS TimesRated,
		(SELECT AVG(a.RatingValue) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID) AS AverageRating
	FROM adn_RatingDetails r
	WHERE NOT itemid IN (SELECT ItemID FROM adn_RatingDetailsGlobalized WHERE LCID = @LCID)
	ORDER BY ItemOrder ASC
	ELSE 
	EXEC adn_GetRatingDetails @ModuleID
END
ELSE
BEGIN
	IF EXISTS (SELECT 1 FROM adn_RatingDetailsGlobalized g INNER JOIN adn_RatingDetails r ON g.ItemID = r.ItemID WHERE r.ModuleID = @ModuleID AND g.LCID = @LCID)
	SELECT  g.ItemID,
		r.ModuleID,
		r.ItemOrder,
		g.Title,
		g.Description,
		r.CrmEntityID,
		r.CrmID,
		r.CrmCampaignID,
		r.CrmImageID,
		(SELECT COUNT(a.RatingItemID) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID) AS TimesRated,
		(SELECT AVG(a.RatingValue) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID) AS AverageRating
	FROM adn_RatingDetailsGlobalized g INNER JOIN adn_RatingDetails r ON g.ItemID = r.ItemID WHERE r.ModuleID = @ModuleID AND g.LCID = @LCID
	UNION
	SELECT ItemID,
		ModuleID,
		ItemOrder,
		Title,
		[Description],
		CrmEntityID,
		r.CrmID,
		r.CrmCampaignID,
		r.CrmImageID,
		(SELECT COUNT(a.RatingItemID) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID) AS TimesRated,
		(SELECT AVG(a.RatingValue) FROM adn_RatingAnswer a WHERE a.RatingItemID = r.ItemID) AS AverageRating
	FROM adn_RatingDetails r WHERE ModuleID = @ModuleID 
	AND NOT itemid IN (SELECT g.ItemID FROM adn_RatingDetailsGlobalized g INNER JOIN adn_RatingDetails r ON g.ItemID = r.ItemID WHERE r.ModuleID = @ModuleID AND g.LCID = @LCID)
	ORDER BY ItemOrder ASC
	ELSE 
	EXEC adn_GetRatingDetails @ModuleID
END
GO

CREATE PROCEDURE [dbo].[adn_UpdateRatingDetailGlobalized]
(
	@LCID int,
	@DefLCID int,
    @ItemID         int,
	@ItemOrder		int,
    @Title          nvarchar(250),
	@CrmEntityID	uniqueidentifier,
	@CrmCampaignID	uniqueidentifier,
	@CrmImageID		uniqueidentifier,
    @Description    nvarchar(max)
)
AS
IF EXISTS (SELECT 1 FROM adn_RatingDetailsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
BEGIN
	UPDATE adn_RatingDetailsGlobalized
	SET Title           = @Title,
		Description     = @Description
	WHERE ItemID = @ItemID AND LCID = @LCID
	UPDATE adn_RatingDetails
	SET ItemOrder		= @ItemOrder,
		CrmEntityID		= @CrmEntityID,
		CrmCampaignID	= @CrmCampaignID,
		CrmImageID		= @CrmImageID
	WHERE ItemID = @ItemID 
END
ELSE
BEGIN
	IF ( @LCID = @DefLCID )
		EXEC adn_UpdateRatingDetail @ItemID,@ItemOrder,@Title,@CrmEntityID,@CrmCampaignID,@CrmImageID,@Description
	ELSE
	BEGIN
		INSERT INTO adn_RatingDetailsGlobalized
		(
			LCID,
			ItemID,
			Title,
			Description
		)
		VALUES
		(
			@LCID,
			@ItemID,
			@Title,
			@Description
		)
		UPDATE adn_RatingDetails
		SET ItemOrder		= @ItemOrder,
			CrmEntityID		= @CrmEntityID,
			CrmCampaignID	= @CrmCampaignID,
			CrmImageID		= @CrmImageID
		WHERE ItemID = @ItemID 
	END
END
GO

CREATE PROCEDURE [dbo].[adn_DeleteRatingdetailGlobalized]
(
    @ItemID int
)
AS
BEGIN TRAN
DELETE FROM adn_RatingDetails WHERE ItemID = @ItemID
IF ( @@error = 0 )
DELETE FROM adn_RatingDetailsGlobalized WHERE ItemID = @ItemID
IF ( @@error = 0 )
BEGIN
	COMMIT
	RETURN 1
	END
ELSE ROLLBACK
RETURN 0
GO

CREATE PROCEDURE [dbo].[adn_GetSingleRatingDetailGlobalized]
(
	@LCID		int,
	@DefLCID	int,
    @ItemID		int
)
AS
IF EXISTS (SELECT 1 FROM adn_RatingDetailsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
	SELECT  g.ItemID,
		r.ModuleID,
		r.ItemOrder,
		g.Title,
		g.Description,
		r.CrmID,
		r.CrmEntityID,
		r.CrmCampaignID,
		r.CrmImageID,
		COALESCE ((SELECT COUNT(r.RatingItemID) FROM adn_RatingAnswer r WHERE r.RatingItemID = r.ItemID),0) AS TimesRated,
		COALESCE ((SELECT AVG(r.RatingValue) FROM adn_RatingAnswer r WHERE r.RatingItemID = r.ItemID),0) AS AverageRating
	FROM adn_RatingDetailsGlobalized g INNER JOIN adn_RatingDetails r ON g.ItemID = r.ItemID WHERE g.ItemID = @ItemID AND g.LCID = @LCID
ELSE
	SELECT ItemID,
		ModuleID,
		ItemOrder,
		Title,
		[Description],
		CrmID,
		CrmEntityID,
		CrmCampaignID,
		CrmImageID,
		COALESCE ((SELECT COUNT(r.RatingItemID) FROM adn_RatingAnswer r WHERE r.RatingItemID = r.ItemID),0) AS TimesRated,
		COALESCE ((SELECT AVG(r.RatingValue) FROM adn_RatingAnswer r WHERE r.RatingItemID = r.ItemID),0) AS AverageRating
	FROM  adn_RatingDetails WHERE  ItemID = @ItemID
GO

-- RatingAnswer sps
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddRatingAnswer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddRatingAnswer]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetRatingAnswersByRatingItem]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetRatingAnswersByRatingItem]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetRatingAnswersByModule]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetRatingAnswersByModule]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateRatingAnswer]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateRatingAnswer]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateRatingAnswerCrmID]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateRatingAnswerCrmID]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAverageRating]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAverageRating]
GO


CREATE PROCEDURE [dbo].[adn_AddRatingAnswer]
(
	@RatingItemID   int,
	@RatingValue	[float],
	@IPAddress		[nvarchar](200),
    @UserName		[nvarchar] (100), 
    @UserId			uniqueidentifier,
    @EMail			[nvarchar] (100),
	@Phone			[nvarchar] (100),
	@Address		[nvarchar] (250),
    @City			[nvarchar] (100),
    @Zip			[nvarchar] (50),
    @Country		[nvarchar] (100),
    @Comments		[nvarchar] (1000),
    @ItemID         int OUTPUT
)
AS
INSERT INTO adn_RatingAnswer
(
	RatingItemID,
	RatingValue,	
	CreatedDate,
    IPAddress,
    UserName,
    UserId,
    EMail,
	Phone,
	Address,
    City,
    Zip,
    Country,
    Comments
)
VALUES
(
	@RatingItemID,
	@RatingValue,	
	GETUTCDATE(),
    @IPAddress,
    @UserName,
    @UserId,
    @EMail,
	@Phone,
	@Address,
    @City,
    @Zip,
    @Country,
    @Comments
)
SELECT @ItemID = @@Identity
GO

CREATE PROCEDURE [dbo].[adn_GetRatingAnswersByRatingItem]
(
    @RatingItemID int
)
AS
IF ( @RatingItemID = 0 )
	SELECT * FROM adn_RatingAnswer ORDER BY RatingItemID, CreatedDate DESC
ELSE
	SELECT * FROM adn_RatingAnswer WHERE RatingItemID = @RatingItemID ORDER BY CreatedDate DESC
GO

CREATE PROCEDURE [dbo].[adn_GetRatingAnswersByModule]
(
    @ModuleID int
)
AS
IF ( @ModuleID = 0 )
	SELECT * FROM adn_RatingAnswer ORDER BY RatingItemID, CreatedDate DESC
ELSE
	SELECT d.ModuleID,d.Title,d.CrmEntityID,a.* FROM adn_RatingAnswer a INNER JOIN adn_RatingDetails d ON a.ItemID = d.ItemID WHERE d.ModuleID = @ModuleID ORDER BY RatingItemID, CreatedDate DESC
GO

CREATE PROCEDURE [dbo].[adn_UpdateRatingAnswer]
(
    @ItemID         int,
	@RatingItemID   int,
	@RatingValue	[float],	
    @IPAddress		[nvarchar](200),
    @UserName		[nvarchar] (100), 
    @UserId			uniqueidentifier,
    @EMail			[nvarchar] (100),
	@Phone			[nvarchar] (100),
	@Address		[nvarchar] (250),
    @City			[nvarchar] (100),
    @Zip			[nvarchar] (50),
    @Country		[nvarchar] (100),
    @Comments		[nvarchar] (1000)
)
AS
UPDATE adn_RatingAnswer
SET RatingItemID=	@RatingItemID,
	RatingValue	=	@RatingValue,
	IPAddress	=   @IPAddress,
    UserName	=	@UserName,
    UserId		=	@UserId,
    EMail		=	@EMail,
	Phone		=	@Phone,
	Address		=	@Address,
    City		=	@City,
    Zip			=	@Zip,
    Country		=	@Country,
    Comments	=	@Comments
	WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_UpdateRatingAnswerCrmID]
(
    @ItemID			int,
	@CrmID			[uniqueidentifier]
)
AS
UPDATE adn_RatingAnswer SET CrmID = @CrmID WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_GetAverageRating]
(
    @RatingItemID	int,
    @TimesRated	int OUTPUT,
    @AverageRating	float OUTPUT
)
AS
	SELECT @TimesRated=COALESCE(COUNT(RatingItemID),0),@AverageRating = COALESCE(AVG(RatingValue),0) FROM adn_RatingAnswer WHERE RatingItemID = @RatingItemID
GO


-- MediaPlayerLib
-- 16/11
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_MediaPlayerLib]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [dbo].[adn_MediaPlayerLib] (
	[MDPID] [int] IDENTITY (1, 1) NOT NULL ,
	[ModuleID] [int] NOT NULL ,
	[MDPCategory] [nvarchar] (50) NOT NULL ,
	[MDPTitle] [nvarchar] (150) NOT NULL ,
	[MDPCreatedDate] [datetime] NOT NULL ,
	[MDPModifiedDate] [datetime] NOT NULL ,
	[MDPLength] [int] NOT NULL DEFAULT (0),
	[MDPType] [nvarchar] (10) NULL ,
	[MDPType2] [int] NOT NULL DEFAULT (0),
	[MDPUrl] [nvarchar] (150) NULL ,
	[MDPDescription] [nvarchar] (2000) NULL ,
	CONSTRAINT [PK_adn_MediaPlayerLib] PRIMARY KEY NONCLUSTERED 
	(
		[MDPID]
	),
	CONSTRAINT [FK_adn_MediaPlayerLib_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
)
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'.[adn_AddMediaPlayerUrl]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddMediaPlayerUrl]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteMediaPlayerUrl]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteMediaPlayerUrl]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetMediaPlayerLib]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetMediaPlayerLib]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleMediaPlayerUrl]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleMediaPlayerUrl]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateMediaPlayerUrl]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateMediaPlayerUrl]
GO

CREATE PROCEDURE [dbo].[adn_AddMediaPlayerUrl]
(
    @ModuleID       int,
	@MDPCategory	nvarchar(50),
	@MDPLength		int,
	@MDPType		nvarchar(10),
	@MDPType2		int,
    @MDPTitle       nvarchar(150),
    @MDPUrl			nvarchar(150),
    @MDPDescription nvarchar(2000),
    @MDPID         int OUTPUT
)
AS
INSERT INTO adn_MediaPlayerLib
(
    ModuleID,
    MDPCreatedDate,
    MDPModifiedDate,
	MDPCategory,
	MDPLength,
	MDPType,
	MDPType2,
    MDPTitle,
    MDPUrl,
    MDPDescription
)
VALUES
(
    @ModuleID,
    GETUTCDATE(),
    GETUTCDATE(),
	@MDPCategory,
	@MDPLength,
	@MDPType,
	@MDPType2,
    @MDPTitle,
    @MDPUrl,
    @MDPDescription
)
SELECT @MDPID = @@Identity
GO

CREATE PROCEDURE [dbo].[adn_DeleteMediaPlayerUrl]
(
    @MDPID int
)
AS
DELETE FROM adn_MediaPlayerLib WHERE MDPID = @MDPID
GO

CREATE PROCEDURE [dbo].[adn_GetMediaPlayerLib]
(
    @ModuleID int
)
AS
SELECT * FROM adn_MediaPlayerLib WHERE ModuleID = @ModuleID ORDER BY MDPCreatedDate DESC
GO

CREATE PROCEDURE [dbo].[adn_GetSingleMediaPlayerUrl]
(
    @MDPID int
)
AS
SELECT * FROM adn_MediaPlayerLib WHERE MDPID = @MDPID
GO

CREATE PROCEDURE [dbo].[adn_UpdateMediaPlayerUrl]
(
    @MDPID				int,
	@MDPCategory		nvarchar(50),
	@MDPLength			int,
	@MDPType			nvarchar(10),
	@MDPType2			int,
    @MDPTitle			nvarchar(150),
    @MDPUrl				nvarchar(150),
    @MDPDescription		nvarchar(2000)
)
AS
UPDATE adn_MediaPlayerLib
SET MDPModifiedDate =	GETUTCDATE(),
	MDPCategory		=	@MDPCategory,
	MDPLength		=	@MDPLength,
	MDPType			=	@MDPType,
	MDPType2		=	@MDPType2,
    MDPTitle        =	@MDPTitle,
    MDPUrl			=	@MDPUrl,
    MDPDescription  =	@MDPDescription
WHERE MDPID = @MDPID
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetMediaPlayerLibGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetMediaPlayerLibGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateMediaPlayerUrlGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateMediaPlayerUrlGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteMediaPlayerUrlGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteMediaPlayerUrlGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleMediaPlayerUrlGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleMediaPlayerUrlGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetMediaPlayerCategoriesGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetMediaPlayerCategoriesGlobalized]
GO

-- 16/11
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_MediaPlayerLibGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_MediaPlayerLibGlobalized] 
(
	[LCID]	[int] NOT NULL,
	[MDPID] [int] NOT NULL ,
	[ModuleID] [int] NOT NULL ,
	[MDPCategory] [nvarchar] (50) NOT NULL ,
	[MDPTitle] [nvarchar] (150) NOT NULL ,
	[MDPCreatedDate] [datetime] NOT NULL ,
	[MDPModifiedDate] [datetime] NOT NULL ,
	[MDPLength] [int] NOT NULL DEFAULT (0),
	[MDPType] [nvarchar] (10) NULL ,
	[MDPType2] [int] NOT NULL DEFAULT (0),
	[MDPUrl] [nvarchar] (150) NULL ,
	[MDPDescription] [nvarchar] (2000) NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_MediaPlayerLibGlobalized] ADD 
	CONSTRAINT [PK_adn_MediaPlayerLibGlobalized] PRIMARY KEY NONCLUSTERED 
	(
		[LCID],
		[MDPID]
	)  ON [PRIMARY] 

ALTER TABLE [dbo].[adn_MediaPlayerLibGlobalized] ADD 
	CONSTRAINT [FK_adn_MediaPlayerLibGlobalized_adn_MediaPlayerLib] FOREIGN KEY 
	(
		[MDPID]
	) REFERENCES [dbo].[adn_MediaPlayerLib] (
		[MDPID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 

ALTER TABLE [dbo].[adn_MediaPlayerLibGlobalized] ADD 
	CONSTRAINT [FK_adn_MediaPlayerLibGlobalized_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE NO ACTION  NOT FOR REPLICATION 
END
GO

CREATE PROCEDURE [dbo].[adn_GetMediaPlayerCategoriesGlobalized]
(
    @LCID			int,
    @DefLCID		int,
    @ModuleID		int
)
AS
IF EXISTS (SELECT 1 FROM adn_MediaPlayerLibGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
SELECT DISTINCT MDPCategory
FROM adn_MediaPlayerLibGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID
UNION
SELECT DISTINCT MDPCategory FROM adn_MediaPlayerLib
WHERE ModuleID = @ModuleID 
AND NOT MDPCategory IN (SELECT DISTINCT MDPCategory FROM adn_MediaPlayerLibGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
ORDER BY MDPCategory DESC
ELSE 
SELECT DISTINCT MDPCategory FROM adn_MediaPlayerLib WHERE ModuleID = @ModuleID ORDER BY MDPCategory DESC
GO

CREATE PROCEDURE [dbo].[adn_GetMediaPlayerLibGlobalized]
(
    @LCID			int,
    @DefLCID		int,
    @ModuleID		int
)
AS
IF EXISTS (SELECT 1 FROM adn_MediaPlayerLibGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
SELECT MDPID,
    MDPCreatedDate,
	MDPModifiedDate,
	MDPCategory,
	MDPLength,
	MDPType,
	MDPType2,
    MDPTitle,
    MDPUrl,
    MDPDescription
FROM adn_MediaPlayerLibGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID
UNION
SELECT MDPID,
    MDPCreatedDate,
	MDPModifiedDate,
	MDPCategory,
	MDPLength,
	MDPType,
	MDPType2,
    MDPTitle,
    MDPUrl,
    MDPDescription
FROM adn_MediaPlayerLib
WHERE ModuleID = @ModuleID 
AND NOT MDPID IN (SELECT MDPID FROM adn_MediaPlayerLibGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
ORDER BY MDPCreatedDate DESC
ELSE 
EXEC adn_GetMediaPlayerLib @ModuleID
GO

CREATE PROCEDURE [dbo].[adn_DeleteMediaPlayerUrlGlobalized]
(
    @MDPID int
)
AS
BEGIN TRAN
DELETE FROM adn_MediaPlayerLib WHERE MDPID = @MDPID
IF ( @@error = 0 )
DELETE FROM adn_MediaPlayerLibGlobalized WHERE MDPID = @MDPID
IF ( @@error = 0 )
BEGIN
	COMMIT
	RETURN 1
	END
ELSE ROLLBACK
RETURN 0
GO

-- 16/11
CREATE PROCEDURE [dbo].[adn_UpdateMediaPlayerUrlGlobalized]
(
	@LCID			int,
	@DefLCID		int,
    @MDPID			int,
    @ModuleID		int,
	@MDPCategory	nvarchar(50),
	@MDPLength		int,
	@MDPType		nvarchar(10),
	@MDPType2		int,
    @MDPTitle       nvarchar(150),
    @MDPUrl			nvarchar(150),
    @MDPDescription nvarchar(2000)
)
AS
IF EXISTS (SELECT 1 FROM adn_MediaPlayerLibGlobalized WHERE MDPID = @MDPID AND LCID = @LCID)
UPDATE adn_MediaPlayerLibGlobalized
SET MDPModifiedDate =	GETUTCDATE(),
	MDPCategory		=	@MDPCategory,
	MDPLength		=	@MDPLength,
	MDPType			=	@MDPType,
	MDPType2		=	@MDPType2,
    MDPTitle		=	 @MDPTitle,
    MDPUrl			=	@MDPUrl,
    MDPDescription	=	@MDPDescription
WHERE MDPID = @MDPID AND LCID = @LCID
ELSE
BEGIN
IF ((@LCID = @DefLCID ) OR ( @MDPID <= 0 ) )
	EXEC adn_UpdateMediaPlayerUrl @MDPID,@MDPCategory,@MDPLength,@MDPType,@MDPType2,@MDPTitle,@MDPUrl,@MDPDescription
ELSE
INSERT INTO adn_MediaPlayerLibGlobalized
(
    LCID,
    MDPID,
    ModuleID,
    MDPCreatedDate,
    MDPModifiedDate,
	MDPCategory,
	MDPLength,
	MDPType,
	MDPType2,
    MDPTitle,
    MDPUrl,
    MDPDescription
)
VALUES
(
    @LCID,
    @MDPID,
    @ModuleID,
    GETUTCDATE(),
    GETUTCDATE(),
	@MDPCategory,
	@MDPLength,
	@MDPType,
	@MDPType2,
	@MDPTitle,
    @MDPUrl,
    @MDPDescription
)
END
GO

CREATE PROCEDURE [dbo].[adn_GetSingleMediaPlayerUrlGlobalized]
(
	@LCID		int,
	@DefLCID	int,
    @MDPID		int
)
AS
IF EXISTS (SELECT 1 FROM adn_MediaPlayerLibGlobalized WHERE MDPID = @MDPID AND LCID = @LCID)
SELECT * FROM  adn_MediaPlayerLibGlobalized WHERE MDPID = @MDPID AND LCID = @LCID
ELSE
SELECT * FROM adn_MediaPlayerLib WHERE MDPID = @MDPID
GO

-- Enhanced HTML
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_EnhancedHtml]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_EnhancedHtml] (
	[ItemID] [int] IDENTITY (1, 1) NOT NULL ,
	[ModuleID] [int] NOT NULL ,
	[CreatedByUser] [nvarchar] (100) NULL ,
	[CreatedDate] [datetime] NULL ,
	[Title] [nvarchar] (100) NULL ,
	[ViewOrder] [int] NULL ,
	[CultureCode] [int] NULL,
	[DesktopHtml] [nvarchar](max) NOT NULL ,
	CONSTRAINT [PK_adn_EnhancedHtml] PRIMARY KEY NONCLUSTERED 
	(
		[ItemID]
	),
	CONSTRAINT [FK_adn_EnhancedHtml_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
)
END
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_AddEnhancedHtml]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddEnhancedHtml]
GO

CREATE PROCEDURE [dbo].[adn_AddEnhancedHtml]
(
    @ModuleID    int,
    @UserName    nvarchar(100),
    @Title       nvarchar(100),
    @ViewOrder   int,
    @CultureCode int,
    @DesktopHtml nvarchar(max),
    @ItemID      int OUTPUT
)
AS
INSERT INTO adn_EnhancedHtml
(
    ModuleID,
    CreatedByUser,
    CreatedDate,
    Title,
    ViewOrder,
    CultureCode,
    DesktopHtml
)
VALUES
(
    @ModuleID,
    @UserName,
    GETUTCDATE(),
    @Title,
    @ViewOrder,
    @CultureCode,
    @DesktopHtml
)
SELECT @ItemID = SCOPE_IDENTITY()
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteEnhancedHtml]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteEnhancedHtml]
GO

CREATE PROCEDURE [dbo].[adn_DeleteEnhancedHtml]
(
    @ItemID int
)
AS
DELETE FROM adn_EnhancedHtml WHERE ItemID = @ItemID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetEnhancedHtml]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetEnhancedHtml]
GO

CREATE PROCEDURE [dbo].[adn_GetEnhancedHtml]
(
    @ModuleID int
)
AS
SELECT ItemID,
    CreatedByUser,
    CreatedDate,
    Title,
    ViewOrder,
    CultureCode,
    DesktopHtml
FROM adn_EnhancedHtml WHERE ModuleID = @ModuleID ORDER BY ViewOrder
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetEnhancedLocalizedHtml]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetEnhancedLocalizedHtml]
GO

CREATE PROCEDURE [dbo].[adn_GetEnhancedLocalizedHtml]
(
    @ModuleID int,
    @CultureCode int
)
AS
SELECT ItemID,
    Title,
    DesktopHtml
FROM adn_EnhancedHtml
WHERE (ModuleID = @ModuleID) AND (CultureCode = @CultureCode)
ORDER BY ViewOrder
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleEnhancedHtml]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleEnhancedHtml]
GO

CREATE PROCEDURE [dbo].[adn_GetSingleEnhancedHtml]
(
    @ItemID int
)
AS
SELECT CreatedByUser,
    CreatedDate,
    Title,
    ViewOrder,
    CultureCode,
    DesktopHtml
FROM adn_EnhancedHtml WHERE ItemID = @ItemID
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateEnhancedHtml]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateEnhancedHtml]
GO

CREATE PROCEDURE [dbo].[adn_UpdateEnhancedHtml]
(
    @ItemID      int,
    @UserName    nvarchar(100),
    @Title       nvarchar(100),
    @ViewOrder   int,
    @CultureCode int,
    @DesktopHtml nvarchar(max)
)
AS
UPDATE adn_EnhancedHtml
SET CreatedByUser = @UserName,
    CreatedDate   = GETUTCDATE(),
    Title         = @Title,
    ViewOrder     = @ViewOrder,
    CultureCode   = @CultureCode,
    DesktopHtml   = @DesktopHtml
WHERE ItemID = @ItemID
GO

-- EnhancedLinks
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_AddEnhancedLink]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddEnhancedLink]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteEnhancedLink]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteEnhancedLink]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetEnhancedLinks]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetEnhancedLinks]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetEnhancedLinksGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetEnhancedLinksGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleEnhancedLink]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleEnhancedLink]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleEnhancedLinkGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleEnhancedLinkGlobalized]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateEnhancedLink]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateEnhancedLink]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateEnhancedLinkGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateEnhancedLinkGlobalized]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_EnhancedLinks]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_EnhancedLinks] (
	[ItemID] [int] IDENTITY (1, 1) NOT NULL ,
	[ModuleID] [int] NOT NULL ,
	[CreatedByUser] [nvarchar] (100) NULL ,
	[CreatedDate] [datetime] NULL ,
	[Title] [nvarchar] (100) NULL ,
	[Url] [nvarchar] (800) NULL ,
	[ViewOrder] [int] NULL ,
	[Description] [nvarchar] (2000) NULL ,
    [ImageUrl] [nvarchar] (250) NULL,
    [Clicks] [int] NULL,
    [Target] [nvarchar] (10) NOT NULL DEFAULT ('_new')
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_EnhancedLinks] ADD
	CONSTRAINT [PK_adn_EnhancedLinks] PRIMARY KEY NONCLUSTERED 
	(
		[ItemID]
	)  ON [PRIMARY] 

ALTER TABLE [dbo].[adn_EnhancedLinks] ADD
	CONSTRAINT [FK_adn_EnhancedLinks_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_EnhancedLinksGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_EnhancedLinksGlobalized] (
	[LCID]		[int] NOT NULL,
	[ItemID] [int] NOT NULL ,
	[ModuleID] [int] NOT NULL ,
	[CreatedByUser] [nvarchar] (100) NULL ,
	[CreatedDate] [datetime] NULL ,
	[Title] [nvarchar] (100) NULL ,
	[Url] [nvarchar] (800) NULL ,
	[ViewOrder] [int] NULL ,
	[Description] [nvarchar] (2000) NULL ,
    [ImageUrl] [nvarchar] (250) NULL,
    [Clicks] [int] NULL,
    [Target] [nvarchar] (10) NOT NULL DEFAULT ('_new')
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_EnhancedLinksGlobalized] ADD 
	CONSTRAINT [PK_adn_EnhancedLinksGlobalized] PRIMARY KEY NONCLUSTERED 
	(
		[LCID],
		[ItemID]
	)  ON [PRIMARY] 
ALTER TABLE [dbo].[adn_EnhancedLinksGlobalized] ADD 
	CONSTRAINT [PK_adn_EnhancedLinksGlobalized_adn_EnhancedLinks] FOREIGN KEY 
	(
		[ItemID]
	) REFERENCES [dbo].[adn_EnhancedLinks] (
		[ItemID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
ALTER TABLE [dbo].[adn_EnhancedLinksGlobalized] ADD 
	CONSTRAINT [PK_adn_EnhancedLinksGlobalized_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE NO ACTION  NOT FOR REPLICATION 
END
GO

CREATE PROCEDURE [dbo].[adn_AddEnhancedLink]
(
    @ModuleID    int,
    @UserName    nvarchar(100),
    @Title       nvarchar(100),
    @Url         nvarchar(800),
    @ViewOrder   int,
    @Description nvarchar(2000),
    @ImageUrl    nvarchar(250),
    @Clicks      int,
    @Target	     nvarchar(10),
    @ItemID      int OUTPUT
)
AS
INSERT INTO adn_EnhancedLinks
(
    ModuleID,
    CreatedByUser,
    CreatedDate,
    Title,
    Url,
    ViewOrder,
    Description,
    ImageUrl,
    Clicks,
    Target
)
VALUES
(
    @ModuleID,
    @UserName,
    GETUTCDATE(),
    @Title,
    @Url,
    @ViewOrder,
    @Description,
    @ImageUrl,
    @Clicks,
    @Target
)
SELECT @ItemID = @@Identity
GO

CREATE PROCEDURE [dbo].[adn_DeleteEnhancedLink]
(
    @ItemID int
)
AS
DELETE FROM  adn_EnhancedLinks WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_GetEnhancedLinks]
(
    @ModuleID int
)
AS
SELECT ItemID,
    CreatedByUser,
    CreatedDate,
    Title,
    Url,
    ViewOrder,
    Description,
    ImageUrl,
    Clicks,
    Target
FROM adn_EnhancedLinks WHERE ModuleID = @ModuleID ORDER BY ViewOrder
GO

CREATE PROCEDURE [dbo].[adn_GetSingleEnhancedLink]
(
    @ItemID int
)
AS
SELECT CreatedByUser,
    CreatedDate,
    Title,
    Url,
    ViewOrder,
    Description,
    ImageUrl,
    Clicks,
    Target
FROM adn_EnhancedLinks WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_UpdateEnhancedLink]
(
    @ItemID      int,
    @UserName    nvarchar(100),
    @Title       nvarchar(100),
    @Url         nvarchar(800),
    @ViewOrder   int,
    @Description nvarchar(2000),
    @ImageUrl	 nvarchar(250),
    @Clicks      int,
    @Target		 nvarchar(10)
)
AS
UPDATE adn_EnhancedLinks
SET CreatedByUser = @UserName,
    CreatedDate   = GETUTCDATE(),
    Title         = @Title,
    Url           = @Url,
    ViewOrder     = @ViewOrder,
    Description   = @Description,
    ImageUrl      = @ImageUrl,
    Clicks        = @Clicks,
    Target		  = @Target
WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_GetEnhancedLinksGlobalized]
(
    @LCID			int,
    @DefLCID		int,
    @ModuleID int
)
AS
IF EXISTS (SELECT 1 FROM adn_EnhancedLinksGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
SELECT ItemID,
    CreatedByUser,
    CreatedDate,
    Title,
    Url,
    ViewOrder,
    Description,
    ImageUrl,
    Clicks,
    Target
FROM adn_EnhancedLinksGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID
UNION
SELECT ItemID,
	    CreatedByUser,
	    CreatedDate,
	    Title,
	    Url,
	    ViewOrder,
	    Description,
	    ImageUrl,
	    Clicks,
	    Target
FROM adn_EnhancedLinks WHERE ModuleID = @ModuleID
AND NOT itemid IN (SELECT ItemID FROM adn_EnhancedLinksGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID) 
ORDER BY ViewOrder	    
ELSE 
EXEC adn_GetEnhancedLinks @ModuleID
GO

CREATE PROCEDURE [dbo].[adn_GetSingleEnhancedLinkGlobalized]
(
	@LCID		int,
	@DefLCID	int,
    @ItemID int
)
AS
IF EXISTS (SELECT 1 FROM adn_EnhancedLinksGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
SELECT CreatedByUser,
    CreatedDate,
    Title,
    Url,
    ViewOrder,
    Description,
    ImageUrl,
    Clicks,
    Target
FROM adn_EnhancedLinksGlobalized WHERE ItemID = @ItemID AND LCID = @LCID
ELSE
SELECT CreatedByUser,
    CreatedDate,
    Title,
    Url,
    ViewOrder,
    Description,
    ImageUrl,
    Clicks,
    Target
FROM adn_EnhancedLinks WHERE  ItemID = @ItemID	    
GO

CREATE PROCEDURE [dbo].[adn_UpdateEnhancedLinkGlobalized]
(
	@LCID int,
	@DefLCID int,
    @ItemID      int,
    @ModuleID		int,
    @UserName    nvarchar(100),
    @Title       nvarchar(100),
    @Url         nvarchar(800),
    @ViewOrder   int,
    @Description nvarchar(2000),
    @ImageUrl	 nvarchar(250),
    @Clicks      int,
    @Target		 nvarchar(10)
)
AS
IF EXISTS (SELECT 1 FROM adn_EnhancedLinksGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
UPDATE adn_EnhancedLinksGlobalized
SET CreatedByUser = @UserName,
    CreatedDate   = GETUTCDATE(),
    Title         = @Title,
    Url           = @Url,
    ViewOrder     = @ViewOrder,
    Description   = @Description,
    ImageUrl      = @ImageUrl,
    Clicks        = @Clicks,
    Target		  = @Target
WHERE ItemID = @ItemID AND LCID = @LCID
ELSE
BEGIN
IF ( @LCID = @DefLCID )
	EXEC adn_UpdateEnhancedLink @ItemID,@UserName,@Title,@Url,@ViewOrder,@Description,@ImageUrl,@Clicks,@Target
ELSE
INSERT INTO adn_EnhancedLinksGlobalized
(
	LCID,
	ItemID,
	ModuleID ,
	CreatedByUser,
	CreatedDate,
	Title,
	Url,
	ViewOrder,
	Description,
    ImageUrl,
    Clicks,
    Target
    )
VALUES
(
	@LCID,
    @ItemID,
    @ModuleID,
    @UserName,
    GETUTCDATE(),
    @Title,
    @Url,
    @ViewOrder,
    @Description,
    @ImageUrl,
    @Clicks,
    @Target		
)
END
GO

-- FAQ
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateFAQs]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateFAQs]
GO
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetSingleFAQs]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleFAQs]
GO
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetFAQs]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFAQs]
GO
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeleteFAQs]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteFAQs]
GO
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_AddFAQs]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddFAQs]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteFAQsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteFAQsGlobalized]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetFAQsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetFAQsGlobalized]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleFAQsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleFAQsGlobalized]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateFAQsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateFAQsGlobalized]
GO
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_FAQs]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_FAQs] (
[ItemID] [int] IDENTITY (1, 1) NOT NULL ,
[ModuleID] [int] NOT NULL ,
[CreatedByUser] [nvarchar] (100) NULL ,
[CreatedDate] [datetime] NULL ,
[Question] [nvarchar] (400) NULL ,
[Answer] [nvarchar] (max) NULL 
) ON [PRIMARY] 

ALTER TABLE [dbo].[adn_FAQs] WITH NOCHECK ADD 
	CONSTRAINT [PK_adn_FAQs] PRIMARY KEY  CLUSTERED 
	(
	[ItemID]
	)  ON [PRIMARY] 
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_FAQsGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_FAQsGlobalized] (
	[LCID]		[int] NOT NULL,
	[ItemID] [int]	NOT NULL ,
	[ModuleID] [int] NOT NULL ,
	[CreatedByUser] [nvarchar] (100)  NULL ,
	[CreatedDate] [datetime] NULL ,
	[Question] [nvarchar] (400) NULL ,
	[Answer] [nvarchar] (max) NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_FAQsGlobalized] WITH NOCHECK ADD 
	CONSTRAINT [PK_adn_FAQsGlobalized] PRIMARY KEY  CLUSTERED 
	(
	[LCID],
	[ItemID]
	)  ON [PRIMARY] 
END
GO

CREATE PROCEDURE [dbo].[adn_AddFAQs]
	(@ItemID 	[int] OUTPUT,
	 @ModuleID 	[int],
	 @UserName	[nvarchar] (100),
	 @Question 	[nvarchar] (400),
	 @Answer 	[nvarchar] (max))
AS INSERT INTO [adn_FAQs]
	([ModuleID],
	 [CreatedByUser],
	 [CreatedDate],
	 [Question],
	 [Answer]) 
VALUES 
	 (@ModuleID,
	  @UserName,
	  GETUTCDATE(),
	  @Question,
	  @Answer)
SELECT @ItemID = @@IDENTITY
GO

CREATE PROCEDURE [dbo].[adn_DeleteFAQs]
	(@ItemID 	[int])
AS 
DELETE FROM [adn_FAQs] WHERE [ItemID] = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_GetFAQs]
(@ModuleID int)
AS
SELECT ItemID, CreatedByUser, CreatedDate, Question, Answer FROM adn_FAQs 
WHERE ModuleID = @ModuleID ORDER BY Question
GO

CREATE PROCEDURE [dbo].[adn_GetSingleFAQs]
(@ItemID int)
AS
SELECT CreatedByUser, CreatedDate, Question, Answer FROM adn_FAQs
WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_UpdateFAQs]
	(@ItemID 	[int],
	 @UserName	[nvarchar] (100),
	 @Question 	[nvarchar] (400),
	 @Answer 	[nvarchar] (max))
AS 
UPDATE [adn_FAQs]
SET  [CreatedByUser] = @UserName,
	 [Question]	 = @Question,
	 [Answer]	 = @Answer 
WHERE ( [ItemID]	 = @ItemID)
GO

CREATE PROCEDURE [dbo].[adn_GetFAQsGlobalized]
(
@ModuleID int,
@LCID int,
@DefLCID int
)
AS
IF EXISTS (SELECT 1 FROM adn_FAQsGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
SELECT ItemID, CreatedByUser, CreatedDate, Question , Answer FROM adn_FAQsGlobalized
WHERE ModuleID = @ModuleID AND LCID = @LCID 
UNION
SELECT ItemID, CreatedByUser, CreatedDate, Question , Answer 
FROM adn_FAQs WHERE ModuleID = @ModuleID AND not itemid in (select ItemID FROM adn_FAQsGlobalized
				WHERE ModuleID = @ModuleID AND LCID = @LCID)
ORDER BY Question 
ELSE 
EXEC adn_GetFAQs @ModuleID
GO

CREATE PROCEDURE [dbo].[adn_UpdateFAQsGlobalized]
(
	@ModuleID int,
	@ItemID int,
	@LCID int,
	@DefLCID int,
	 @UserName	[nvarchar] (100),
	 @Question 	[nvarchar] (400),
	 @Answer 	[nvarchar] (max))
AS 
IF EXISTS (SELECT 1 FROM adn_FAQsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
UPDATE [adn_FAQsGlobalized]
SET [CreatedByUser] = @UserName,
	 [Question]	 = @Question,
	 [Answer]	 = @Answer 
WHERE ( [ItemID]	 = @ItemID) AND LCID = @LCID
ELSE
BEGIN
if ( @LCID = @DefLCID )
	EXEC adn_UpdateFAQs @ItemID,@UserName,@Question,@Answer
ELSE
-- first time we copy all records
INSERT INTO [adn_FAQsGlobalized]
	(LCID, ItemID,ModuleID,CreatedByUser,CreatedDate,Question,Answer)
	VALUES
	(@LCID,@ItemID,@ModuleID,@UserName,GETUTCDATE(),@Question,@Answer)
END
GO

CREATE PROCEDURE [dbo].[adn_GetSingleFAQsGlobalized ]
(
@ItemID int,
@LCID int,
@DefLCID int
)
AS
IF EXISTS (SELECT 1 FROM adn_FAQsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
SELECT CreatedByUser, CreatedDate, Question, Answer FROM adn_FAQsGlobalized
WHERE ItemID = @ItemID AND LCID = @LCID
ELSE
EXEC adn_GetSingleFAQs @ItemID
GO


CREATE PROCEDURE [dbo].[adn_DeleteFAQsGlobalized]
	(@ItemID 	[int])
AS 
BEGIN TRAN
DELETE FROM [adn_FAQs]
WHERE [ItemID] = @ItemID
IF ( @@error = 0 )
DELETE FROM [adn_FAQsGlobalized]
WHERE [ItemID] = @ItemID
IF ( @@error = 0 )
BEGIN
	COMMIT
	RETURN 1
	END
ELSE ROLLBACK
RETURN 0
GO

-- Magic Urls
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateMagicUrls]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateMagicUrls]
GO
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetSingleMagicUrls]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleMagicUrls]
GO
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetAllMagicUrls]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllMagicUrls]
GO
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetMagicUrls]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetMagicUrls]
GO
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeleteMagicUrls]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteMagicUrls]
GO
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_AddMagicUrls]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddMagicUrls]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_DeleteMagicUrlsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteMagicUrlsGlobalized]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAllMagicUrlsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllMagicUrlsGlobalized]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetMagicUrlsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetMagicUrlsGlobalized]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetSingleMagicUrlsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleMagicUrlsGlobalized]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UpdateMagicUrlsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateMagicUrlsGlobalized]
GO
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_MagicUrls]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_MagicUrls] (
[ItemID] [int] IDENTITY (1, 1) NOT NULL ,
[PortalID] [int] NOT NULL, 
[MagicKey] [nvarchar] (128) NOT NULL ,
[MagicValue] [nvarchar] (512) NOT NULL, 
[MagicComment] [nvarchar] (512) NULL,
[MagicScheduleDay] [int] NOT NULL, 
[MagicScheduleHours] [int] NOT NULL 
) ON [PRIMARY] 

ALTER TABLE [dbo].[adn_MagicUrls] WITH NOCHECK ADD 
	CONSTRAINT [PK_adn_MagicUrls] PRIMARY KEY  CLUSTERED 
	(
	[ItemID]
	)  ON [PRIMARY] 

CREATE UNIQUE NONCLUSTERED INDEX [adn_MagicUrlsKey_IDX] ON [dbo].[adn_MagicUrls] 
(
	[MagicKey] ASC
) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_MagicUrlsGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_MagicUrlsGlobalized] (
	[LCID] [int] NOT NULL,
	[ItemID] [int]	NOT NULL ,
	[PortalID] [int] NOT NULL, 
	[MagicKey] [nvarchar] (128) NULL ,
	[MagicValue] [nvarchar] (512) NULL,
	[MagicComment] [nvarchar] (512) NULL,
	[MagicScheduleDay] [int] NOT NULL, 
	[MagicScheduleHours] [int] NOT NULL 
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_MagicUrlsGlobalized] WITH NOCHECK ADD 
	CONSTRAINT [PK_adn_MagicUrlsGlobalized] PRIMARY KEY  CLUSTERED 
	(
	[LCID],
	[ItemID]
	)  ON [PRIMARY] 
END
GO

CREATE PROCEDURE [dbo].[adn_AddMagicUrls]
(
	@ItemID 	[int] OUTPUT,
	@PortalID	[int], 
	@MagicKey 	[nvarchar] (128),
	@MagicValue 	[nvarchar] (512),
	@MagicComment 	[nvarchar] (512),
	@MagicScheduleDay [int], 
	@MagicScheduleHours [int]
)
AS 
INSERT INTO [adn_MagicUrls]
(
	[PortalID],
	[MagicKey],
	[MagicValue], 
	[MagicComment],
	[MagicScheduleDay], 
	[MagicScheduleHours]
)
VALUES 
(
	@PortalID, 
	@MagicKey,
	@MagicValue,
	@MagicComment,
	@MagicScheduleDay, 
	@MagicScheduleHours
)
SELECT @ItemID = @@IDENTITY
GO

CREATE PROCEDURE [dbo].[adn_DeleteMagicUrls]
	(@ItemID 	[int])
AS 
DELETE FROM [adn_MagicUrls] WHERE [ItemID] = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_GetAllMagicUrls]
AS
SELECT * FROM adn_MagicUrls ORDER BY MagicKey
GO

CREATE PROCEDURE [dbo].[adn_GetMagicUrls]
	(@PortalID 	[int])
AS
SELECT * FROM adn_MagicUrls WHERE PortalID = @PortalID ORDER BY MagicKey
GO

CREATE PROCEDURE [dbo].[adn_GetSingleMagicUrls ]
(@ItemID int)
AS
SELECT * FROM adn_MagicUrls WHERE ItemID = @ItemID
GO

CREATE PROCEDURE [dbo].[adn_UpdateMagicUrls]
(
	@ItemID 	[int],
	@MagicKey 	[nvarchar] (128),
	@MagicValue 	[nvarchar] (512),
	@MagicComment 	[nvarchar] (512),
	@MagicScheduleDay [int], 
	@MagicScheduleHours [int]
)
AS UPDATE [adn_MagicUrls]
SET  [MagicKey]		= @MagicKey,
	[MagicValue]	= @MagicValue,
	MagicComment	= @MagicComment,
	MagicScheduleDay= @MagicScheduleDay, 
	MagicScheduleHours=@MagicScheduleHours
WHERE ( [ItemID]	 = @ItemID)
GO


CREATE PROCEDURE [dbo].[adn_GetAllMagicUrlsGlobalized]
(
@LCID int,
@DefLCID int
)
AS
IF EXISTS (SELECT 1 FROM adn_MagicUrlsGlobalized WHERE LCID = @LCID)
SELECT 	 ItemID,MagicKey,MagicValue,MagicComment,MagicScheduleDay,MagicScheduleHours
 FROM adn_MagicUrlsGlobalized
WHERE LCID = @LCID 
UNION
SELECT ItemID,MagicKey,MagicValue,MagicComment,MagicScheduleDay,MagicScheduleHours FROM adn_MagicUrls WHERE not itemid in (select ItemID FROM adn_MagicUrlsGlobalized
				WHERE LCID = @LCID)
ORDER BY MagicKey 
ELSE 
EXEC adn_GetAllMagicUrls
GO

CREATE PROCEDURE [dbo].[adn_GetMagicUrlsGlobalized]
(
@LCID int,
@DefLCID int,
@PortalID int
)
AS
IF EXISTS (SELECT 1 FROM adn_MagicUrlsGlobalized WHERE LCID = @LCID AND PortalID=@PortalID)
SELECT 	 ItemID,MagicKey,MagicValue,MagicComment,MagicScheduleDay,MagicScheduleHours
 FROM adn_MagicUrlsGlobalized
WHERE LCID = @LCID AND PortalID=@PortalID
UNION
SELECT ItemID,MagicKey,MagicValue,MagicComment,MagicScheduleDay,MagicScheduleHours FROM adn_MagicUrls 
	WHERE PortalID=@PortalID AND not itemid in (select ItemID FROM adn_MagicUrlsGlobalized	WHERE LCID = @LCID AND PortalID=@PortalID)
ORDER BY MagicKey 
ELSE 
EXEC adn_GetMagicUrls @PortalID
GO

CREATE PROCEDURE [dbo].[adn_UpdateMagicUrlsGlobalized]
(
	@ItemID int,
	@LCID int,
	@DefLCID int,
	@MagicKey 	[nvarchar] (128),
	@MagicValue 	[nvarchar] (512),
	@MagicComment 	[nvarchar] (512),
	@MagicScheduleDay [int], 
	@MagicScheduleHours [int]
)
AS 
IF EXISTS (SELECT 1 FROM adn_MagicUrlsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
UPDATE [adn_MagicUrlsGlobalized]
SET [MagicKey]		= @MagicKey,
	[MagicValue]	= @MagicValue,
	MagicComment	= @MagicComment,
	MagicScheduleDay= @MagicScheduleDay, 
	MagicScheduleHours=@MagicScheduleHours
WHERE ( [ItemID]	 = @ItemID) AND LCID = @LCID
ELSE
BEGIN
IF ( @LCID = @DefLCID )
	EXEC adn_UpdateMagicUrls @ItemID,@MagicKey,@MagicValue,@MagicComment,@MagicScheduleDay,@MagicScheduleHours
ELSE
-- first time we copy all records
INSERT INTO [adn_MagicUrlsGlobalized]
	(LCID, ItemID,MagicKey,MagicValue,MagicComment,MagicScheduleDay,MagicScheduleHours)
	VALUES
	(@LCID,@ItemID,@MagicKey,@MagicValue,@MagicComment,@MagicScheduleDay,@MagicScheduleHours)
END
GO

CREATE PROCEDURE [dbo].[adn_GetSingleMagicUrlsGlobalized ]
(
@ItemID int,
@LCID int,
@DefLCID int
)
AS
IF EXISTS (SELECT 1 FROM adn_MagicUrlsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
SELECT * FROM adn_MagicUrlsGlobalized
WHERE ItemID = @ItemID AND LCID = @LCID
ELSE 
EXEC adn_GetSingleMagicUrls @ItemID
GO


CREATE PROCEDURE [dbo].[adn_DeleteMagicUrlsGlobalized]
	(@ItemID 	[int])
AS 
BEGIN TRAN
DELETE FROM [adn_MagicUrls]
WHERE ( [ItemID] = @ItemID)
IF ( @@error = 0 )
DELETE FROM [adn_MagicUrlsGlobalized]
WHERE ( [ItemID] = @ItemID)
IF ( @@error = 0 )
BEGIN
	COMMIT
	RETURN 1
END
ELSE ROLLBACK
RETURN 0
GO

-- Add default values
declare @item int
IF NOT EXISTS (SELECT * FROM dbo.adn_MagicUrls)
BEGIN
EXEC adn_AddMagicUrls @item,0,'Home','0','Portal base page',0,0
EXEC adn_AddMagicUrls @item,0,'adn','http://www.addonnice.com','Addon Nice site',0,0
END
GO


-- Contact
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_Contacts]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_Contacts] (
	[ItemID] [int] IDENTITY (1,1)NOT NULL ,
	[ModuleID] [int] NOT NULL ,
	[CreatedByUser] [nvarchar] (100) NULL ,
	[CreatedDate] [datetime] NULL ,
	[Name] [nvarchar] (50) NULL ,
	[Role] [nvarchar] (100) NULL ,
	[Email] [nvarchar] (100) NULL ,
	[Contact1] [nvarchar] (250) NULL ,
	[Contact2] [nvarchar] (250) NULL ,
	[Fax] [nvarchar] (250) NULL,
	[Address] [nvarchar] (250) NULL,
	CONSTRAINT [PK_adn_Contacts] PRIMARY KEY NONCLUSTERED 
	(
		[ItemID]
	),
	CONSTRAINT [FK_adn_Contacts_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE CASCADE  NOT FOR REPLICATION 
)
END
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_ContactsGlobalized]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_ContactsGlobalized] (
	[LCID]		[int] NOT NULL,
	[ItemID]	[int] NOT NULL ,
	[ModuleID]	[int] NOT NULL ,
	[CreatedByUser] [nvarchar] (100) NULL ,
	[CreatedDate] [datetime] NULL ,
	[Name] [nvarchar] (50) NULL ,
	[Role] [nvarchar] (100) NULL ,
	[Email] [nvarchar] (100) NULL ,
	[Contact1] [nvarchar] (250) NULL ,
	[Contact2] [nvarchar] (250) NULL ,
	[Fax] [nvarchar] (250) NULL, 
	[Address] [nvarchar] (250) NULL,
	CONSTRAINT [PK_adn_ContactsGlobalized] PRIMARY KEY NONCLUSTERED 
	(
		[LCID],
		[ItemID]
	),
	CONSTRAINT [FK_adn_ContactsGlobalized_adn_Contacts] FOREIGN KEY 
	(
		[ItemID]
	) REFERENCES [dbo].[adn_Contacts] (
		[ItemID]
	) ON DELETE CASCADE  NOT FOR REPLICATION ,

	CONSTRAINT [adn_ContactsGlobalized_adn_Modules] FOREIGN KEY 
	(
		[ModuleID]
	) REFERENCES [dbo].[adn_Modules] (
		[ModuleID]
	) ON DELETE NO ACTION  NOT FOR REPLICATION 
)
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_AddContact]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddContact]
GO

CREATE PROCEDURE [dbo].[adn_AddContact]
(
    @ModuleID int,
    @UserName nvarchar(100),
    @Name     nvarchar(50),
    @Role     nvarchar(100),
    @Email    nvarchar(100),
    @Contact1 nvarchar(250),
    @Contact2 nvarchar(250),
    @Fax nvarchar(250),
    @Address nvarchar(250),
    @ItemID   int OUTPUT
)
AS
INSERT INTO adn_Contacts
(
    CreatedByUser,
    CreatedDate,
    ModuleID,
    [Name],
    Role,
    Email,
    Contact1,
    Contact2,
    Fax,
    Address
)
VALUES
(
    @UserName,
    GETUTCDATE(),
    @ModuleID,
    @Name,
    @Role,
    @Email,
    @Contact1,
    @Contact2,
    @Fax,
    @Address
)
SELECT @ItemID = @@IDENTITY
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeleteContact]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteContact]
GO

CREATE PROCEDURE [dbo].[adn_DeleteContact]
(
    @ItemID int
)
AS
DELETE FROM  adn_Contacts WHERE ItemID = @ItemID
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_DeleteContactGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_DeleteContactGlobalized]
GO

CREATE PROCEDURE [dbo].[adn_DeleteContactGlobalized]
	(@ItemID 	[int])
AS 
BEGIN TRAN
DELETE FROM adn_Contacts WHERE ( [ItemID] = @ItemID)
IF ( @@error = 0 )
DELETE FROM [adn_ContactsGlobalized] WHERE ( [ItemID] = @ItemID)
IF ( @@error = 0 )
BEGIN
	COMMIT
	RETURN 1
	END
ELSE ROLLBACK
RETURN 0
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetContacts]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetContacts]
GO

CREATE PROCEDURE [dbo].[adn_GetContacts]
(
    @ModuleID int
)
AS
SELECT  ItemID,
    CreatedDate,
    CreatedByUser,
    [Name],
    Role,
    Email,
    Contact1,
    Contact2,
    Fax,
    Address
FROM adn_Contacts WHERE ModuleID = @ModuleID ORDER BY [Name]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetContactsGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetContactsGlobalized]
GO

CREATE PROCEDURE [dbo].[adn_GetContactsGlobalized]
(
    @LCID			int,
    @DefLCID		int,
    @ModuleID       int
)
AS
IF EXISTS (SELECT 1 FROM adn_ContactsGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID)
SELECT ItemID,
    CreatedDate,
    CreatedByUser,
    [Name],
    Role,
    Email,
    Contact1,
    Contact2,
    Fax,
    Address
FROM adn_ContactsGlobalized WHERE ModuleID = @ModuleID AND LCID = @LCID
UNION	
SELECT ItemID,
	    CreatedDate,
	    CreatedByUser,
	    [Name],
	    Role,
	    Email,
	    Contact1,
	    Contact2,
	    Fax,
	    Address
FROM adn_Contacts WHERE ModuleID = @ModuleID 
AND NOT itemid IN (SELECT ItemID FROM adn_ContactsGlobalized	WHERE ModuleID = @ModuleID AND LCID = @LCID)
ORDER BY [Name]	
ELSE 
EXEC adn_GetContacts @ModuleID
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetSingleContact]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleContact]
GO

CREATE PROCEDURE [dbo].[adn_GetSingleContact]
(
    @ItemID         int
)
AS
SELECT CreatedByUser,
    CreatedDate,
    [Name],
    Role,
    Email,
    Contact1,
    Contact2,
    Fax,
    Address
FROM adn_Contacts WHERE ItemID = @ItemID 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_GetSingleContactGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetSingleContactGlobalized]
GO

CREATE PROCEDURE [dbo].[adn_GetSingleContactGlobalized]
(
    @LCID			int,
    @DefLCID		int,
    @ItemID         int
)
AS
IF EXISTS (SELECT 1 FROM adn_ContactsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
SELECT CreatedByUser,
    CreatedDate,
    [Name],
    Role,
    Email,
    Contact1,
    Contact2,
    Fax,
    Address
FROM adn_ContactsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID
UNION
SELECT CreatedByUser,
	    CreatedDate,
	    Name,
	    Role,
	    Email,
	    Contact1,
	    Contact2,
	    Fax,
	    Address
FROM adn_Contacts WHERE ItemID = @ItemID  
AND NOT itemid IN (SELECT ItemID FROM adn_ContactsGlobalized	WHERE ItemID = @ItemID AND LCID = @LCID)   
ELSE
EXEC adn_GetSingleContact @ItemID
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateContact]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateContact]
GO

CREATE PROCEDURE [dbo].[adn_UpdateContact]
(
    @ItemID   int,
    @UserName nvarchar(100),
    @Name     nvarchar(50),
    @Role     nvarchar(100),
    @Email    nvarchar(100),
    @Contact1 nvarchar(250),
    @Contact2 nvarchar(250),
    @Fax nvarchar(250),
    @Address nvarchar(250)
)
AS
UPDATE adn_Contacts
SET CreatedByUser = @UserName,
    CreatedDate   = GETUTCDATE(),
    [Name]        = @Name,
    Role          = @Role,
    Email         = @Email,
    Contact1      = @Contact1,
    Contact2      = @Contact2,
    Fax			  = @Fax,
    Address       = @Address
WHERE ItemID = @ItemID
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_UpdateContactGlobalized]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_UpdateContactGlobalized]
GO

CREATE PROCEDURE [dbo].[adn_UpdateContactGlobalized]
(
	@LCID int,
	@DefLCID int,
    @ItemID   int,
    @ModuleID		int,
    @UserName nvarchar(100),
    @Name     nvarchar(50),
    @Role     nvarchar(100),
    @Email    nvarchar(100),
    @Contact1 nvarchar(250),
    @Contact2 nvarchar(250),
    @Fax nvarchar(250),
    @Address nvarchar(250)
)
AS
IF EXISTS (SELECT 1 FROM adn_ContactsGlobalized WHERE ItemID = @ItemID AND LCID = @LCID)
UPDATE adn_ContactsGlobalized
SET CreatedByUser = @UserName,
    CreatedDate   = GETUTCDATE(),
    [Name]          = @Name,
    Role          = @Role,
    Email         = @Email,
    Contact1      = @Contact1,
    Contact2      = @Contact2,
    Fax			  = @Fax,
    Address       = @Address
WHERE ItemID = @ItemID
ELSE
BEGIN
IF ( @LCID = @DefLCID )
	EXEC adn_UpdateContact @ItemID,@UserName,@Name,@Role,@Email,@Contact1,@Contact2,@Fax,@Address
ELSE
INSERT INTO adn_ContactsGlobalized
(
	[LCID],
	[ItemID],
	[ModuleID],
	[CreatedByUser],
	[CreatedDate],
	[Name],
	[Role],
	[Email],
	[Contact1],
	[Contact2]
)
VALUES
(
	@LCID,
    @ItemID,
    @ModuleID,
    @UserName,
    GETUTCDATE(),
    @Name,
    @Role,
    @Email,
    @Contact1,
    @Contact2
)
END
GO


-- Utility tables
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_GetAllUserCivilites]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllUserCivilites]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[adn_UserCivilite]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_UserCivilite] (
	[CiviliteId] [int] NOT NULL ,
	[CiviliteLCID] [int] NOT NULL,
	[CiviliteTxt] [nvarchar] (50)  NOT NULL ,
) ON [PRIMARY]

ALTER TABLE [dbo].[adn_UserCivilite] WITH NOCHECK ADD 
	CONSTRAINT [PK_adn_UserCivilite] PRIMARY KEY  CLUSTERED 
	(
		[CiviliteId],
		[CiviliteLCID] 
	)  ON [PRIMARY] 

INSERT INTO [dbo].[adn_UserCivilite]
(	[CiviliteId],[CiviliteLCID],[CiviliteTxt])
SELECT 	1,9,'Mr.'
UNION ALL
SELECT 	2,9,'Mrs.'
UNION ALL
SELECT 	3,9,'Miss'
UNION ALL
SELECT 	4,9,'Herrn'
UNION ALL
SELECT 	5,9,'Frau'
UNION ALL
SELECT 	6,9,'Dr.'
UNION ALL
SELECT 	1,12,'M.'
UNION ALL
SELECT 	2,12,'Mme'
UNION ALL
SELECT 	3,12,'Mlle'
UNION ALL
SELECT 	4,12,'Herrn'
UNION ALL
SELECT 	5,12,'Frau'
UNION ALL
SELECT 	6,12,'Dr'
END
GO

CREATE PROCEDURE dbo.adn_GetAllUserCivilites
(
	@CiviliteLangID [int]
)
AS
SELECT CiviliteId,CiviliteTxt FROM adn_UserCivilite WHERE CiviliteLCID = @CiviliteLangID ORDER BY CiviliteId
GO

-- Monitoring users
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_Monitoring]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_Monitoring] 
(
	[ID] [int] IDENTITY (1, 1) NOT NULL ,
	[Logtype] [int] NOT NULL CONSTRAINT [DF_adn_Monitoring_LogType]  DEFAULT (0),
	[UserID] [uniqueIdentifier] NULL ,
	[typeCode] [int] NULL ,
	[CrmUserID] [uniqueIdentifier] NULL ,
	[PortalID] [int] NULL ,
	[PageID] [int] NULL ,
	[ModuleID] [int] NULL ,
	[ItemID] [int] NULL ,
	[CrmItemID] [uniqueIdentifier] NULL ,
	[ActivityTime] [datetime] NULL ,
	[ActivityType] [nvarchar] (50) NULL ,
	[Referrer] [nvarchar] (255) NULL ,
	[UserAgent] [nvarchar] (100) NULL ,
	[UserHostAddress] [nvarchar] (15) NULL ,
	[BrowserType] [nvarchar] (100) NULL ,
	[BrowserName] [nvarchar] (100) NULL ,
	[BrowserVersion] [nvarchar] (100) NULL ,
	[BrowserPlatform] [nvarchar] (100) NULL ,
	[UserField] [nvarchar] (500) NULL,
-- new
	[UserName] [nvarchar] (100) NULL,
	[IsCrawler] [bit] NULL,
-- replace [BrowserIsAOL] [bit] NULL
	[IsUnderCRM] [bit] NULL, 
	[IsCallBack] [bit] NULL,
) ON [PRIMARY]
END
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_AddMonitoringEntry]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddMonitoringEntry]
GO

CREATE PROCEDURE [dbo].[adn_AddMonitoringEntry]
	@Logtype int,
    @UserID uniqueidentifier,
    @typeCode int,
    @CrmUserID uniqueidentifier,
    @PortalID int,
    @PageID int,
    @ModuleID int,
    @ItemID int,
    @CrmItemID uniqueidentifier,
    @ActivityType nvarchar(50),
    @Referrer nvarchar(255),
    @UserAgent nvarchar(100),
    @UserHostAddress nvarchar(15),
    @BrowserType nvarchar(100),
    @BrowserName nvarchar(100),
    @BrowserVersion nvarchar(100),
    @BrowserPlatform nvarchar(100),
	@UserName nvarchar(100),
	@IsCrawler bit,
	@IsUnderCRM bit, 
	@IsCallBack bit,
    @UserField nvarchar(500)
AS
INSERT INTO adn_Monitoring
(
	Logtype ,
    UserID,
    typeCode,
    CrmUserID,
    PortalID,
    PageID,
    ModuleID,
    ItemID,
    CrmItemID,
    ActivityTime,
    ActivityType,
    Referrer,
    UserAgent,
    UserHostAddress,
    BrowserType,
    BrowserName,
    BrowserVersion,
    BrowserPlatform,
	UserName,
	IsCrawler,
	IsUnderCRM, 
	IsCallBack,
    UserField
)
VALUES
(
	@Logtype,
    @UserID,
    @typeCode,
    @CrmUserID,
    @PortalID,
    @PageID,
    @ModuleID,
    @ItemID,
    @CrmItemID,
    GETUTCDATE(),
    @ActivityType,
    @Referrer,
    @UserAgent,
    @UserHostAddress,
    @BrowserType,
    @BrowserName,
    @BrowserVersion,
    @BrowserPlatform,
	@UserName,
	@IsCrawler,
	@IsUnderCRM, 
	@IsCallBack,
    @UserField
)
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetMonitoringEntries]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetMonitoringEntries]
GO

CREATE PROCEDURE [dbo].[adn_GetMonitoringEntries] 
(
    @PortalID				int,
    @StartDate				datetime,
    @EndDate				datetime,
    @ReportType				int,
    @LogType				int,
    @CurrentTabID			int,
    @IPAddress				nvarchar(200),
    @SearchData				nvarchar(200),
    @IncludeMonitorPage		bit,
    @IncludeAdminUser		bit,
    @IncludePageRequests	bit,
    @IncludeLogon			bit,
    @IncludeLogoff			bit,
    @IncludeIPAddress		bit,
    @IncludeUnderCRM		bit,
    @IncludeCallBack		bit,
    @IncludeCrawler			bit
)
AS

	SET NOCOUNT ON

	DECLARE @SQLSTRING nvarchar(2000)

--	IF (UPPER(@ReportType) = 'DETAILED SITE LOG')
	IF ( @ReportType = 0)
	BEGIN
		SET @SQLSTRING = 'SELECT adnm.*,wtt.TabName FROM dbo.adn_Monitoring adnm ' +
					'INNER JOIN adn_Portals wtp ON adnm.PortalID = wtp.PortalID LEFT OUTER JOIN adn_Tabs wtt ON adnm.PageID = wtt.TabID ' +
					'WHERE ActivityTime >= ''' + CAST(@StartDate AS nvarchar) + ''' AND ActivityTime <= ''' + CAST(@EndDate AS nvarchar) + '''  ' +
					'AND adnm.PortalID = ' + CAST(@PortalID AS nvarchar)
		IF (@IncludeMonitorPage = 0) 
			SET @SQLSTRING = @SQLSTRING + ' AND adnm.PageID != ' + CAST(@CurrentTabID AS nvarchar) + ' '
		IF (@IncludePageRequests = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND ActivityType != ''PageRequest'' '
		IF (@IncludeLogon = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND ActivityType != ''Logon'' '
		IF (@IncludeLogoff = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND ActivityType != ''Logoff'' '
		IF (@IncludeIPAddress = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND UserHostAddress != ''' + @IPAddress + ''' '
		IF (@IncludeUnderCRM = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsUnderCRM != ''1'' '
		IF (@IncludeCallBack = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsCallBack != ''1'' '
		IF (@IncludeCrawler = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsCrawler != ''1'' '
		SET @SQLSTRING = @SQLSTRING + ' ORDER BY ActivityTime DESC'
	END
	ELSE
--	IF (UPPER(@ReportType) = 'DETAILED HOST LOG')
	IF ( @ReportType = 9)
	BEGIN
		SET @SQLSTRING = 'SELECT adnm.*,wtt.TabName FROM dbo.adn_Monitoring adnm  ' +
					'INNER JOIN adn_Portals wtp ON adnm.PortalID = wtp.PortalID LEFT OUTER JOIN adn_Tabs wtt ON adnm.PageID = wtt.TabID ' +
					'WHERE ActivityTime >= ''' + CAST(@StartDate AS nvarchar) + ''' AND ActivityTime <= ''' + CAST(@EndDate AS nvarchar) + '''  ' +
					'AND adnm.PortalID = ' + CAST(@PortalID AS nvarchar) +
					' AND UserHostAddress LIKE ''' + @IPAddress + '''  ORDER BY ActivityTime DESC'
	END
	ELSE
--	IF (UPPER(@ReportType) = 'PAGE POPULARITY')
	IF ( @ReportType = 1 )
	BEGIN
		SET @SQLSTRING = 'SELECT wtt.TabName, ''Requests'' = count(*), ''LastRequest'' = max(ActivityTime) ' +
					'FROM dbo.adn_Monitoring adnm INNER JOIN adn_Tabs wtt ON adnm.PageID = wtt.TabID ' +
					'WHERE ActivityTime >= ''' + CAST(@StartDate AS nvarchar) + ''' AND ActivityTime <= ''' + CAST(@EndDate AS nvarchar) + '''  ' +
					'AND adnm.PortalID = ' + CAST(@PortalID AS nvarchar) + ' AND adnm.ActivityType=''PageRequest''' 
		IF (@IncludeIPAddress = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND UserHostAddress != ''' + @IPAddress + ''' '
		IF (@IncludeUnderCRM = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsUnderCRM != ''1'' '
		IF (@IncludeCallBack = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsCallBack != ''1'' '
		IF (@IncludeCrawler = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsCrawler != ''1'' '
		SET @SQLSTRING = @SQLSTRING + ' GROUP BY wtt.TabName ORDER BY Requests DESC'
	END
	ELSE
--	IF (UPPER(@ReportType) = 'MOST ACTIVE WEB USERS')
	IF ( @ReportType = 2 )
	BEGIN
		SET @SQLSTRING = 'SELECT adnu.UserName, ''Actions'' = count(*), ''LastAction'' = max(ActivityTime) ' +
					'FROM dbo.adn_Monitoring adnm INNER JOIN AddonNice_Users adnu ON adnm.UserID = adnu.UserID ' +
					'WHERE ActivityTime >= ''' + CAST(@StartDate AS nvarchar) + ''' AND ActivityTime <= ''' + CAST(@EndDate AS nvarchar) + '''  ' +
					'AND NOT( adnm.CrmItemID = ''00000000-0000-0000-0000-000000000000'' ) ' +
					'AND adnm.PortalID = ' + CAST(@PortalID AS nvarchar) + ' '
		IF (@IncludeMonitorPage = 0) 
			SET @SQLSTRING = @SQLSTRING + 'AND adnm.PageID != ' + CAST(@CurrentTabID AS nvarchar) + ' '
		IF (@IncludePageRequests = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND ActivityType != ''PageRequest'' '
		IF (@IncludeLogon = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND ActivityType != ''Logon'' '
		IF (@IncludeLogoff = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND ActivityType != ''Logoff'' '
		IF (@IncludeIPAddress = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND UserHostAddress != ''' + @IPAddress + ''' '
		IF (@IncludeUnderCRM = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsUnderCRM != ''1'' '
		IF (@IncludeCallBack = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsCallBack != ''1'' '
		IF (@IncludeCrawler = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsCrawler != ''1'' '
		SET @SQLSTRING = @SQLSTRING + ' GROUP BY adnu.UserName ORDER BY Actions DESC'
	END
	ELSE
--	IF (UPPER(@ReportType) = 'MOST WIEWED ITEMS')
	IF ( @ReportType = 3 )
	BEGIN
		SET @SQLSTRING = 'SELECT adnm.ItemID, ''Actions'' = count(*), ''LastAction'' = max(ActivityTime) ' +
					'FROM dbo.adn_Monitoring adnm ' +
					'WHERE ActivityTime >= ''' + CAST(@StartDate AS nvarchar) + ''' AND ActivityTime <= ''' + CAST(@EndDate AS nvarchar) + '''  ' +
					'AND adnm.CrmItemID = ''00000000-0000-0000-0000-000000000000''  ' +
					'AND NOT (adnm.ItemID = 0 ) '+
					'AND adnm.PortalID = ' + CAST(@PortalID AS nvarchar) + ' '
		IF (@IncludeIPAddress = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND UserHostAddress != ''' + @IPAddress + ''' '
		IF (@IncludeUnderCRM = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsUnderCRM != ''1'' '
		IF (@IncludeCallBack = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsCallBack != ''1'' '
		IF (@IncludeCrawler = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsCrawler != ''1'' '
		SET @SQLSTRING = @SQLSTRING + ' GROUP BY adnm.ItemID ORDER BY Actions DESC'
	END
	ELSE
--	IF (UPPER(@ReportType) = 'MOST WIEWED CRMITEMS')
	IF ( @ReportType = 4 )
	BEGIN
		SET @SQLSTRING = 'SELECT adnm.ItemID, adnm.CrmItemID, ''Actions'' = count(*), ''LastAction'' = max(ActivityTime) ' +
					'FROM dbo.adn_Monitoring adnm ' +
					'WHERE ActivityTime >= ''' + CAST(@StartDate AS nvarchar) + ''' AND ActivityTime <= ''' + CAST(@EndDate AS nvarchar) + '''  ' +
					'AND NOT( adnm.CrmItemID = ''00000000-0000-0000-0000-000000000000'' ) ' +
					'AND adnm.PortalID = ' + CAST(@PortalID AS nvarchar) + ' '
		IF (@IncludeIPAddress = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND UserHostAddress != ''' + @IPAddress + ''' '
		IF (@IncludeUnderCRM = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsUnderCRM != ''1'' '
		IF (@IncludeCallBack = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsCallBack != ''1'' '
		IF (@IncludeCrawler = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsCrawler != ''1'' '
		SET @SQLSTRING = @SQLSTRING + ' GROUP BY adnm.ItemID, adnm.CrmItemID ORDER BY Actions DESC'
	END
	ELSE
--	IF (UPPER(@ReportType) = 'DETAILLED CRM ITEMS VIEW')
	IF ( @ReportType = 8 )
	BEGIN
		SET @SQLSTRING = 'SELECT adnm.* ' +
					'FROM dbo.adn_Monitoring adnm ' +
					'WHERE ActivityTime >= ''' + CAST(@StartDate AS nvarchar) + ''' AND ActivityTime <= ''' + CAST(@EndDate AS nvarchar) + '''  ' +
					'AND adnm.ItemID = ' + CAST(@CurrentTabID AS nvarchar) + 
					' AND NOT( adnm.CrmItemID = ''00000000-0000-0000-0000-000000000000'' ) ' +
					'AND adnm.PortalID = ' + CAST(@PortalID AS nvarchar) + ' '
		IF (@IncludeIPAddress = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND UserHostAddress != ''' + @IPAddress + ''' '
		IF (@IncludeUnderCRM = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsUnderCRM != ''1'' '
		IF (@IncludeCallBack = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsCallBack != ''1'' '
		IF (@IncludeCrawler = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsCrawler != ''1'' '
		SET @SQLSTRING = @SQLSTRING + ' ORDER BY ActivityTime DESC'
	END
	ELSE
--	IF (UPPER(@ReportType) = 'PAGE VIEWS BY DAY')
	IF ( @ReportType =  5 )
	BEGIN
		SET @SQLSTRING = 'SELECT ''Date'' = convert(varchar,ActivityTime,102), ''Views'' = count(*), ''Visitors'' = count(distinct UserHostAddress), ''Users'' = count(distinct UserID), ''CrmUsers'' = count(distinct CrmUserID) ' +
					'FROM dbo.adn_Monitoring adnm ' +
					'WHERE ActivityTime >= ''' + CAST(@StartDate AS nvarchar) + ''' AND ActivityTime <= ''' + CAST(@EndDate AS nvarchar) + '''  ' +
					'AND adnm.PortalID = ' + CAST(@PortalID AS nvarchar) + ' AND adnm.ActivityType=''PageRequest'''
		IF (@IncludeIPAddress = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND UserHostAddress != ''' + @IPAddress + ''' '
		IF (@IncludeUnderCRM = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsUnderCRM != ''1'' '
		IF (@IncludeCallBack = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsCallBack != ''1'' '
		IF (@IncludeCrawler = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsCrawler != ''1'' '
		SET @SQLSTRING = @SQLSTRING + ' GROUP BY convert(varchar,ActivityTime,102) ORDER BY [Date] ASC'
	END
	ELSE
--	IF (UPPER(@ReportType) = 'PAGE VIEWS BY BROWSER TYPE')
	IF ( @ReportType = 6 )
	BEGIN
		SET @SQLSTRING = 'SELECT BrowserType, ''Views'' = count(*), ''LastAction'' = max(ActivityTime) ' +
					'FROM dbo.adn_Monitoring adnm ' +
					'WHERE ActivityTime >= ''' + CAST(@StartDate AS nvarchar) + ''' AND ActivityTime <= ''' + CAST(@EndDate AS nvarchar) + '''  ' + 
					'AND ActivityType = ''PageRequest'' ' +
					'AND adnm.PortalID = ' + CAST(@PortalID AS nvarchar) + ' AND adnm.ActivityType=''PageRequest'''
		IF (@IncludeIPAddress = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND UserHostAddress != ''' + @IPAddress + ''' '
		IF (@IncludeUnderCRM = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsUnderCRM != ''1'' '
		IF (@IncludeCallBack = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsCallBack != ''1'' '
		IF (@IncludeCrawler = 0)
			SET @SQLSTRING = @SQLSTRING + ' AND IsCrawler != ''1'' '
		SET @SQLSTRING = @SQLSTRING + ' GROUP BY BrowserType ORDER BY [Views] DESC'
	END
	ELSE
--	IF (UPPER(@ReportType) = 'MOST ACTIVE CRM USERS')
	IF ( @ReportType = 7 )
	BEGIN

		SET @SQLSTRING = 'SELECT adnm.UserName, ''Actions'' = count(*), ''LastAction'' = max(ActivityTime) ' +
					'FROM dbo.adn_Monitoring adnm ' +
					'WHERE ActivityTime >= ''' + CAST(@StartDate AS nvarchar) + ''' AND ActivityTime <= ''' + CAST(@EndDate AS nvarchar) + '''  ' +
					'AND NOT( adnm.CrmUserId = ''00000000-0000-0000-0000-000000000000'' ) ' +
					'AND adnm.PortalID = ' + CAST(@PortalID AS nvarchar) + ' '
		IF (@IncludeIPAddress = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND UserHostAddress != ''' + @IPAddress + ''' '
		IF (@IncludeUnderCRM = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsUnderCRM != ''1'' '
		IF (@IncludeCallBack = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsCallBack != ''1'' '
		IF (@IncludeCrawler = 0)
			SET @SQLSTRING = @SQLSTRING + 'AND IsCrawler != ''1'' '
		SET @SQLSTRING = @SQLSTRING + ' GROUP BY adnm.UserField ORDER BY Actions DESC'
	END
	ELSE
--	IF (UPPER(@ReportType) = 'MOST ACTIVE USERS')
	IF ( @ReportType = 10 )
	BEGIN

		SET @SQLSTRING = 'SELECT  DISTINCT TOP 20 UserHostAddress, count(UserHostAddress) AS Count FROM dbo.adn_Monitoring '+
				'WHERE IsCrawler = 0 AND PortalID = ' + CAST(@PortalID AS nvarchar) + 
				'  AND NOT UserHostAddress like (''' + @IPAddress + ''') GROUP BY UserHostAddress ORDER BY count(UserHostAddress) DESC'
	END
	EXEC (@SQLSTRING)
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetMonitoringEntriesEx]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetMonitoringEntriesEx]
GO

CREATE PROCEDURE [dbo].[adn_GetMonitoringEntriesEx] 
(
    @PortalID				int,
    @StartDate				datetime,
    @EndDate				datetime,
    @CurrentTabs			nvarchar(200),
    @IPAddress				nvarchar(200),
    @SearchData				nvarchar(200),
    @IncludePages			int,
    @IncludeRequests		int,
    @IncludeIPAddress		int,
    @IncludeUnderCRM		int,
    @IncludeCallBack		int,
    @IncludeCrawler			int
)
AS

	SET NOCOUNT ON

	DECLARE @SQLSTRING nvarchar(2000)

	SET @SQLSTRING = 'SELECT adnm.*,wtt.TabName FROM dbo.adn_Monitoring adnm ' +
				'INNER JOIN adn_Portals wtp ON adnm.PortalID = wtp.PortalID LEFT OUTER JOIN adn_Tabs wtt ON adnm.PageID = wtt.TabID ' +
				'WHERE ActivityTime >= ''' + CAST(@StartDate AS nvarchar) + ''' AND ActivityTime <= ''' + CAST(@EndDate AS nvarchar) + '''  ' +
				'AND adnm.PortalID = ' + CAST(@PortalID AS nvarchar)
	IF ( @IncludePages = 0) 
		SET @SQLSTRING = @SQLSTRING + ' AND NOT adnm.PageID IN ' + @CurrentTabs
	ELSE IF (@IncludePages = 1) 
		SET @SQLSTRING = @SQLSTRING + ' AND adnm.PageID IN ' + @CurrentTabs
	IF ( @IncludeRequests = 0)
		SET @SQLSTRING = @SQLSTRING + ' AND NOT LogType IN '+ @SearchData 
	ELSE IF ( @IncludeRequests = 1)
		SET @SQLSTRING = @SQLSTRING + ' AND LogType IN '+ @SearchData 
	IF (@IncludeIPAddress = 0)
		SET @SQLSTRING = @SQLSTRING + ' AND UserHostAddress IN ' + @IPAddress 
	ELSE IF (@IncludeIPAddress = 1)
		SET @SQLSTRING = @SQLSTRING + ' AND NOT UserHostAddress IN ' + @IPAddress 
	IF (@IncludeUnderCRM = 0)
		SET @SQLSTRING = @SQLSTRING + ' AND IsUnderCRM != ''1'' '
	ELSE IF (@IncludeUnderCRM = 1)
		SET @SQLSTRING = @SQLSTRING + ' AND IsUnderCRM = ''1'' '
	IF (@IncludeCallBack = 0)
		SET @SQLSTRING = @SQLSTRING + ' AND IsCallBack != ''1'' '
	ELSE IF (@IncludeCallBack = 1)
		SET @SQLSTRING = @SQLSTRING + ' AND IsCallBack = ''1'' '
	IF (@IncludeCrawler = 0)
		SET @SQLSTRING = @SQLSTRING + ' AND IsCrawler != ''1'' '
	ELSE IF (@IncludeCrawler = 1)
		SET @SQLSTRING = @SQLSTRING + ' AND IsCrawler = ''1'' '
	SET @SQLSTRING = @SQLSTRING + ' ORDER BY ActivityTime DESC'
	EXEC (@SQLSTRING)
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetLoggedOnUsers]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetLoggedOnUsers]
GO

CREATE PROCEDURE [dbo].[adn_GetLoggedOnUsers]
(
    @PortalID    int,
    @MinutesToCheck int
)
AS
	SELECT DISTINCT adnm.UserHostAddress, adnu.UserName, (SELECT TOP 1 ActivityType FROM dbo.adn_Monitoring
		WHERE (ActivityType = 'Logon' OR ActivityType = 'Logoff')
		AND ActivityTime >= DATEADD(n, -@MinutesToCheck, GETUTCDATE())
		AND UserHostAddress = adnm.UserHostAddress
		AND UserID = adnm.UserID
		AND adnm.PortalID = @PortalID
		ORDER BY ActivityTime desc) as LastAction
		FROM dbo.adn_Monitoring adnm
		INNER JOIN AddonNice_Users adnu ON adnm.UserID = adnu.UserID
		WHERE (adnm.ActivityType = 'Logon' or adnm.ActivityType = 'Logoff') 
		AND adnm.ActivityTime >= DATEADD(n, -@MinutesToCheck, GETUTCDATE())
		AND adnm.PortalID = @PortalID
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetNumberOfActiveUsers]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetNumberOfActiveUsers]
GO

CREATE PROCEDURE [dbo].[adn_GetNumberOfActiveUsers]
(
    @PortalID    int,
    @MinutesToCheck int,
    @NoOfUsers int OUTPUT
)
AS
SELECT @NoOfUsers =  Count(distinct UserHostAddress) FROM dbo.adn_Monitoring
WHERE ActivityTime >= DATEADD(n, -@MinutesToCheck, GETUTCDATE())
AND PortalID = @PortalID
GO


-- String Resource for dynamic translations in ascx and aspx
--INSERT INTO adn_StringResources (resourceType, cultureCode, resourceKey, resourceValue) Values ('Glossary', 'en','SiteMap','Site Map')
--INSERT INTO adn_StringResources (resourceType, cultureCode, resourceKey, resourceValue) Values ('Glossary', 'es','SiteMap','Mapa del sitio')
IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_StringResources]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[adn_StringResources](
	[resourceType] [nvarchar](256) NOT NULL,
	[cultureCode] [nvarchar](10) NOT NULL,
	[resourceKey] [nvarchar](128) NOT NULL,
	[resourceValue] [nvarchar](4000) NOT NULL,
 CONSTRAINT [PK_adn_StringResources] PRIMARY KEY CLUSTERED 
(
	[resourceType] ASC,
	[cultureCode] ASC,
	[resourceKey] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_AddStringResource]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_AddStringResource]
GO

CREATE PROCEDURE [dbo].[adn_AddStringResource]
(
	@resourceType [nvarchar](256),
	@cultureCode [nvarchar](10),
	@resourceKey [nvarchar](128),
	@resourceValue [nvarchar](4000)
	)
AS
IF EXISTS (SELECT * FROM adn_StringResources WHERE resourceType=@resourceType AND cultureCode=@cultureCode AND resourceKey=@resourceKey)
UPDATE adn_StringResources SET resourceValue=@resourceValue WHERE resourceType=@resourceType AND cultureCode=@cultureCode AND resourceKey=@resourceKey
ELSE
INSERT INTO adn_StringResources (resourceType,cultureCode,resourceKey,resourceValue) VALUES (@resourceType,@cultureCode,@resourceKey,@resourceValue)
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetStringResource]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetStringResource]
GO

CREATE PROCEDURE [dbo].[adn_GetStringResource]
(
	@resourceType [nvarchar](256),
	@cultureCode [nvarchar](10),
	@resourceKey [nvarchar](128)
	)
AS
SELECT * FROM adn_StringResources WHERE resourceType=@resourceType AND cultureCode=@cultureCode AND resourceKey=@resourceKey
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetAllStringResourceByType]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllStringResourceByType]
GO

CREATE PROCEDURE [dbo].[adn_GetAllStringResourceByType]
(
	@resourceType [nvarchar](256)
	)
AS
SELECT * FROM adn_StringResources WHERE resourceType=@resourceType
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GetAllStringResourceByCountry]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GetAllStringResourceByCountry]
GO

CREATE PROCEDURE [dbo].[adn_GetAllStringResourceByCountry]
(
	@resourceType [nvarchar](256),
	@cultureCode [nvarchar](10)
	)
AS
SELECT * FROM adn_StringResources WHERE resourceType=@resourceType AND cultureCode=@cultureCode
GO

-- sp to grant access to portal DB
-- beware doesn't support transactions

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_GrantAccess]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_GrantAccess]
GO

CREATE PROCEDURE [dbo].[adn_GrantAccess]
(
	@login nvarchar(256),
	@role nvarchar(256)
)
AS	
DECLARE @Stmt nvarchar(4000)
IF NOT EXISTS (SELECT * FROM  master.dbo.syslogins WHERE name = @login )
BEGIN
	SELECT @Stmt = 'CREATE LOGIN '
	SELECT @Stmt = @Stmt + quotename(@login,']')
	SELECT @Stmt = @Stmt + ' FROM WINDOWS'
	EXEC (@Stmt)
--END SQL 2008
--IF NOT EXISTS (SELECT * FROM  master.dbo.sysusers WHERE name = @login )
--BEGIN
SELECT @Stmt = 'CREATE USER '
SELECT @Stmt = @Stmt + quotename(@login,']')
SELECT @Stmt = @Stmt + ' FOR LOGIN '
SELECT @Stmt = @Stmt + quotename(@login,']')
EXEC (@Stmt)
-- EXEC sp_grantdbaccess @login
EXEC sp_addrolemember @role, @login 
END
GO


-------------------------------------------------------------------------------------------------------------------------------
-- SPs used to populate portal UI data
-------------------------------------------------------------------------------------------------------------------------------

--PORTALS
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[adn_Portals_IU]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_Portals_IU]
GO

CREATE PROC [dbo].[adn_Portals_IU]
@PortalID int,  	
@PortalAlias	nvarchar(128),  	
@PortalName	nvarchar(128),  	
@PortalPath	nvarchar(128)
AS  
SET NOCOUNT ON  	
PRINT 'Addon Nice Setup: Adding Portal '+@PortalAlias+' with ID ['+ cast(@PortalID as varchar(10))+']'
UPDATE [adn_Portals] 	
SET PortalAlias = @PortalAlias,  		
	PortalName	= @PortalName,  		
	PortalPath	= @PortalPath
WHERE PortalID	=	@PortalID  	
IF @@rowcount = 0 	
BEGIN 	
	SET IDENTITY_INSERT [adn_Portals] ON 	
	INSERT [adn_Portals] (PortalID, PortalAlias, PortalName, PortalPath) VALUES (@PortalID, @PortalAlias, @PortalName, @PortalPath) 	
	SET IDENTITY_INSERT [adn_Portals] OFF 	
END  
RETURN 
GO


IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_PortalSettings_IU]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_PortalSettings_IU]
GO
CREATE PROC [dbo].[adn_PortalSettings_IU]
@PortalID	int,  	
@SettingName	nvarchar(50),  	
@SettingValue	nvarchar(256)  
AS  
SET NOCOUNT ON  	
UPDATE [adn_PortalSettings] 	
SET SettingValue = @SettingValue 	WHERE PortalID	=	@PortalID AND SettingName	=	@SettingName  	
IF @@ROWCOUNT = 0 	
BEGIN 	
INSERT [adn_PortalSettings] (PortalID, SettingName,  SettingValue) VALUES (@PortalID, @SettingName, @SettingValue) 	
END  
RETURN 
GO

-- Pages
IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_Tabs_IU]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_Tabs_IU]
GO

CREATE PROC [dbo].[adn_Tabs_IU]
@TabID	int, 
@ParentTabID	int,
@TabOrder	int, 
@PortalID	int, 
@TabName	nvarchar(50),
@TabSkinID	nvarchar(50),
@AuthorizedRoles	nvarchar(512),  
@TabLayout	int  
AS  
SET NOCOUNT ON  	
PRINT 'Adding Tab '+@TabName+' with ID ['+ cast(@TabID as varchar(10))+'] ParentTabID: '+ cast(coalesce(@ParentTabID,0) as varchar(10))
UPDATE [adn_Tabs] 	
	SET ParentTabID = @ParentTabID, TabOrder = @TabOrder, PortalID = @PortalID, TabName = @TabName, TabSkinID = @TabSkinID, AuthorizedRoles = @AuthorizedRoles,TabLayout = @TabLayout 	
	WHERE TabID	=	@TabID  	
IF @@ROWCOUNT = 0 	
BEGIN 	
	SET IDENTITY_INSERT [adn_Tabs] ON 	
	INSERT [adn_Tabs] (TabID, ParentTabID, TabOrder, PortalID, TabName, TabSkinID, AuthorizedRoles, TabLayout)VALUES (@TabID, @ParentTabID, @TabOrder, @PortalID, @TabName,@TabSkinID, @AuthorizedRoles, @TabLayout) 	
	SET IDENTITY_INSERT [adn_Tabs] OFF 	
END  
RETURN 
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_TabSettings_IU]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_TabSettings_IU]
GO

CREATE PROC [dbo].[adn_TabSettings_IU]
@TabID	int,  	
@SettingName	nvarchar(50),  	
@SettingValue	nvarchar(256)  
AS  
SET NOCOUNT ON  	
PRINT 'Adding setting '+@SettingName+' value['+ @SettingValue+'] in page '+ cast(@tabID as varchar(10))
UPDATE [adn_TabSettings] 	
SET SettingValue = @SettingValue WHERE TabID = @TabID AND SettingName =	@SettingName  	
IF @@ROWCOUNT = 0 	
BEGIN 	
INSERT [adn_TabSettings] (TabID,SettingName,SettingValue) VALUES (@TabID,@SettingName,@SettingValue) 	
END  
RETURN
GO

-- Modules
IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_Modules_IU]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_Modules_IU]
GO

CREATE PROC [dbo].[adn_Modules_IU]
 	@ModuleID	int,
  	@TabID	int,
  	@GeneralModDefID	uniqueidentifier,
  	@ModuleOrder	int,
  	@PaneName				nvarchar(50),
  	@ModuleTitle			nvarchar(256),
  	@AuthorizedEditRoles	nvarchar(512),
  	@AuthorizedViewRoles	nvarchar(512),
  	@AuthorizedAddRoles		nvarchar(512),
  	@AuthorizedDeleteRoles	nvarchar(512),
  	@AuthorizedPropertiesRoles	nvarchar(512),
  	@CacheTime	int,
  	@NewVersion	bit,
  	@LastModified	datetime,
  	@LastEditor	nvarchar(256),
  	@SupportCollapsable	bit,
  	@ShowEveryWhere		bit ,
  	@AuthorizedMoveModuleRoles	nvarchar(512),
	@AuthorizedDeleteModuleRoles	nvarchar(512)
AS  
IF NOT EXISTS (SELECT ModuleDefID FROM  adn_ModuleDefinitions WHERE GeneralModDefID = @GeneralModDefID )
BEGIN
	RAISERROR('Addon Nice Setup: Something gone wrong. Cannot find the module.', 16, 1)
	RETURN
END
DECLARE @PortalID int
SET @PortalID = 
	(SELECT PortalID FROM  adn_Tabs WHERE TabID = @TabId)   

DECLARE @ModuleDefID int

IF EXISTS (SELECT ModuleDefID FROM  adn_ModuleDefinitions WHERE GeneralModDefID = @GeneralModDefID AND PortalID = @PortalID )
SET @ModuleDefID = (SELECT ModuleDefID FROM  adn_ModuleDefinitions WHERE GeneralModDefID = @GeneralModDefID AND PortalID = @PortalID )
ELSE
SET @ModuleDefID = 
	(SELECT ModuleDefID FROM  adn_ModuleDefinitions WHERE GeneralModDefID = @GeneralModDefID AND PortalID = -2 )

--RAISERROR('Something gone wrong. Cannot find module: ' + CONVERT(varchar(50), @GeneralModDefID) + '''', 16, 1)
PRINT 'Adding module '+@ModuleTitle+' with ID ['+ cast(@ModuleID as varchar(10))+'] in Tab '+ cast(@TabID as varchar(10))
	
SET NOCOUNT ON
UPDATE [adn_Modules] 	
SET TabID = @TabID,
  		ModuleDefID = @ModuleDefID,
  		ModuleOrder = @ModuleOrder,
  		PaneName = @PaneName,
  		ModuleTitle = @ModuleTitle,
  		AuthorizedEditRoles = @AuthorizedEditRoles,
  		AuthorizedViewRoles = @AuthorizedViewRoles,
  		AuthorizedAddRoles = @AuthorizedAddRoles,
  		AuthorizedDeleteRoles = @AuthorizedDeleteRoles,
  		AuthorizedPropertiesRoles = @AuthorizedPropertiesRoles,
  		CacheTime = @CacheTime,
  		NewVersion = @NewVersion,
  		LastModified = @LastModified,
  		LastEditor = @LastEditor,
  		SupportCollapsable = @SupportCollapsable,
  		ShowEveryWhere = @ShowEveryWhere,
		AuthorizedMoveModuleRoles = @AuthorizedMoveModuleRoles,
		AuthorizedDeleteModuleRoles = @AuthorizedDeleteModuleRoles
WHERE ModuleID	=	@ModuleID

IF @@ROWCOUNT = 0 
BEGIN 	
SET IDENTITY_INSERT [adn_Modules] ON 	
	INSERT [adn_Modules] 
		(ModuleID,
  		TabID,
  		ModuleDefID,
  		ModuleOrder,
  		PaneName,
  		ModuleTitle,
  		AuthorizedEditRoles,
  		AuthorizedViewRoles,
  		AuthorizedAddRoles,
  		AuthorizedDeleteRoles,
  		AuthorizedPropertiesRoles,
  		CacheTime,
  		NewVersion,
  		LastModified,
  		LastEditor,
  		SupportCollapsable,
  		ShowEveryWhere,
		AuthorizedMoveModuleRoles,
		AuthorizedDeleteModuleRoles
) 	

VALUES (@ModuleID,
  		@TabID,
  		@ModuleDefID,
  		@ModuleOrder,
  		@PaneName,
  		@ModuleTitle,
  		@AuthorizedEditRoles,
  		@AuthorizedViewRoles,
  		@AuthorizedAddRoles,
  		@AuthorizedDeleteRoles,
  		@AuthorizedPropertiesRoles,
  		@CacheTime,
  		@NewVersion,
  		@LastModified,
  		@LastEditor,
  		@SupportCollapsable,
  		@ShowEveryWhere,
		@AuthorizedMoveModuleRoles,
		@AuthorizedDeleteModuleRoles
) 	SET IDENTITY_INSERT [adn_Modules] OFF 	
END  
RETURN
GO

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'[dbo].[adn_ModuleSettings_IU]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[adn_ModuleSettings_IU]
GO

CREATE PROC [dbo].[adn_ModuleSettings_IU]
@ModuleID	int,  	
@SettingName	nvarchar(50),  	
@SettingValue	nvarchar(256)  
AS  
SET NOCOUNT ON  	
PRINT 'Adding setting '+@SettingName+' value['+ @SettingValue+'] in module '+ cast(@moduleID as varchar(10))
UPDATE [adn_ModuleSettings] 	
SET SettingValue = @SettingValue 	WHERE ModuleID	=	@ModuleID AND SettingName	=	@SettingName  	
IF @@ROWCOUNT = 0 	
BEGIN 	
INSERT [adn_ModuleSettings] (ModuleID,SettingName,SettingValue) 	VALUES (@ModuleID,@SettingName,@SettingValue) 	
END  
RETURN
GO



--2.2.2.0000.sql
-- END
